开发者

Many-to-many sorting in Entity Framework

My application has an Entity Framework model containing a many-to-many relationship like the following:

ProductGroup: 
    Scalar: Id, Name
    Navigation: ProductGroupProduct
Product: 
    Scalar: Id, Sku, Description, etc.
    Navigation: ProductGroupProduct
ProductGroupProduct: 
    Scalar: ProductGroupId, ProductId, Position
    Navigation: Product, ProductGroup

Note how the intermediate table has a scalar property called Position that specifies the order in which a product should be displayed within a product group.

How would you write a LINQ query that returns a list of products in a given product group sorted by the Position property? If I was writing good ol' SQL I'd write something like this:

SELECT p.Id, p.Sku, p.Description
FROM Product p
INNER JOIN ProductGroupProduct pgp ON p.Id = pgp.ProductId 
WHERE pgp.ProductGroupId = @MyProductGroupId 
ORDER BY p开发者_如何学运维gp.Position

But I can't figure the LINQ out.


Um, your SQL won't work, because there is no ProductGroup.Position

But I think you want:

var q = from pgp in Context.ProductGroupProducts
        where pgp.ProductGroup.Id == id
        orderby pgp.Position
        select pgp.Product;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜