实体框架关系查询混淆

时间:2012-03-29 19:02:11

标签: linq entity-framework linq-to-entities

我是EF newb,需要一些帮助来了解如何通过导航属性查询实体。

仅使用C#和LINQ Lambda方法获取此代码:

 List<PublisherImage> images = db.DataModel.PublisherImages.Include("Categories").Where(pi => pi.Enabled && pi.Rendered).OrderBy(pi => pi.ID).ToList();

我需要能够通过类别ID列表过滤此实体,以便按类别获取发布者图像。使用上面的例子,我将如何在SQL(IN语句)中执行我习惯的操作?

有人可以使用C#LINQ Lambda方法而不是LINQ运算符向我展示一个示例吗?

非常感谢!

编辑:

这是我想要做的更好的例子:

 string categoryIds = "1,2,3,4";
 var ids = Array.ConvertAll(categoryIds.Split(','), int.Parse);
 List<PublisherImage> images = db.DataModel.PublisherImages.Include("Categories").Where(pi => pi.Enabled && pi.Rendered && pi.Categories.Where(c => ids.Contains(c.ID)).Any()).OrderBy(pi => pi.ID).ToList();

2 个答案:

答案 0 :(得分:0)

从上一段代码中尝试更改为pi.Categories.Any(c =&gt; ids.Contains(c.ID))

写在我的手机上,很抱歉没有写完整个查询。

答案 1 :(得分:0)

EDIT下的代码确实有效:

 string categoryIds = "1,2,3,4";
 var ids = Array.ConvertAll(categoryIds.Split(','), int.Parse);
 List<PublisherImage> images = db.DataModel.PublisherImages.Include("Categories").Where(pi => pi.Enabled && pi.Rendered && pi.Categories.Where(c => ids.Contains(c.ID)).Any()).OrderBy(pi => pi.ID).ToList();