开发者

How to specify a condition in an Entity Framework join?

开发者 https://www.devze.com 2023-04-06 19:57 出处:网络
I have a Blogs table related to BlogCo开发者_开发百科mments table with a FK. I need to get, through Linq, all the BlogComments items that match a certain flag

I have a Blogs table related to BlogCo开发者_开发百科mments table with a FK.

I need to get, through Linq, all the BlogComments items that match a certain flag

If i do:

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

I get "Cannot implicity convert type IEnumerable to bool"

Which is the best way to solve this problem?


Because this expression:

b.BlogComments.Where(...)

returns an IEnumerable (of BlogComments), but you are then passing it into this method:

db.Blogs.Where(...)

which expects a function that returns a bool, not an IEnumerable.

You probably need something like this:

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

If you need to select comments from multiple blogs, then you could try using Contains:

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

If you want to place criteria on the set of blogs, as well as the comments, then you could do this in one query using a join:

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;


You could write it in LINQ form.

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

If you have a composite key you can write

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


If it were me, I would just have another DbSet in your DbContext.

DbSet<BlogComment> BlogComments

and just search through there without going through Blogs.

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

If anyone knows if there's anything wrong in doing so, then I'm all ears :)

0

精彩评论

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