如何在实体框架连接中指定条件?

时间:2011-09-22 06:23:01

标签: asp.net-mvc entity-framework

我有一个与BlogKments表相关的博客表,附带FK。

我需要通过Linq获取与某个标志匹配的所有BlogComments项目

如果我这样做:

db.Blogs.Where(b => b.BlogComments.Where(bc=>bc.Where(bc.Flag1==true));

我得到“无法将IEnumerable转换为bool”

解决此问题的最佳方法是什么?

3 个答案:

答案 0 :(得分:2)

因为这个表达式:

b.BlogComments.Where(...)

返回一个IEnumerable(BlogComments),但是你将它传递给这个方法:

db.Blogs.Where(...)

它需要一个返回bool的函数,而不是IEnumerable。

你可能需要这样的东西:

var blogId = 5;
db.BlogComments.Where(bc => bc.BlogId == blogId && bc.Flag1 == true)

如果您需要从多个博客中选择评论,那么您可以尝试使用包含:

var blogIds = new [] {1,2,3,4,5};
db.BlogComments.Where(bc => blogIds.Contains(bc.BlogId) && bc.Flag1 == true)

如果您想在博客集上放置条件以及评论,那么您可以使用联接在一个查询中执行此操作:

var query = from b in db.Blogs
            join c in db.BlogComments on c.Blog equals b
            where b.SomeField == "some value"
            && c.Flag1 == true
            select c;

答案 1 :(得分:1)

您可以用LINQ格式编写它。

var blogs = from b in db.Blogs
            join c in db.BlogComments
            on b.BlogId equals c.BlogId
            where c.Flag1
            select b;

如果你有一个复合键,你可以写

on new { A = b.BlogKey1, B = b.BlogKey2 }
  equals new { A = c.CommentKey1, B = c.CommentKey2 }

答案 2 :(得分:0)

如果是我,我会在你的DbContext中有另一个DbSet。

DbSet<BlogComment> BlogComments

只需在不浏览博客的情况下搜索。

db.BlogComments.Where(bc => bc.Flag1 == true);

如果有人知道这样做有什么不对,那么我全都听见了。)

相关问题