2010-01-22 163 views
3

我的应用程序的排序已经包含类似下面的许多一对多关系的实体框架模型:许多一对多的实体框架

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

注意中间表如何有一个名为位置的标属性,指定产品在产品组中显示的顺序。

如何编写一个LINQ查询,返回按Position属性排序的给定产品组中的产品列表?如果我正在编写好的SQL'SQL,我会写这样的东西:

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 pgp.Position 

但我无法找到LINQ。

回答

3

嗯,你的SQL将无法正常工作,因为没有ProductGroup.Position

但我想你想要

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

甜,这就是我所需要的。我一直试图从产品的角度来看它。我没有想到我可以从中间开始。谢谢。 哦,我会修复SQL。这就是我在没有先检查它的情况下将它输入到编辑器中所得到的结果。 – 2010-01-23 13:35:59

+1

你也可以从产品做到这一点,但它更*更难:从Context.Products中的p让pgp =(来自p.ProductGroups中的pgp,其中pgp.ProductGroup.Id == id).FirstOrDefault()其中pgp != null orderby pgp.Position select p;' – 2010-01-23 15:18:42