2011-09-22 29 views
0

我有一個與FK BlogComments表相關的博客表。如何在實體框架連接中指定條件?

我需要通過LINQ中,所有符合一定的標誌

的BlogComments項目如果我做的:

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

我得到 「無法含蓄轉換IEnumerable類型爲bool」

哪個是解決這個問題的最好方法?

回答

2

正因爲如此表達:

b.BlogComments.Where(...) 

返回一個IEnumerable(BlogComments),但然後將它傳遞給此方法:

db.Blogs.Where(...) 

其中一個函數返回一個布爾,不是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; 
0

如果是我,我會在你的DbContext中有另一個DbSet。

DbSet<BlogComment> BlogComments 

只需在那裏搜索,而無需通過博客。

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

如果有誰知道,如果有什麼不對這樣做,那麼我所有的耳朵:)

+0

問題是,我必須提取所有相關的certaint組的博客項目的意見,所以我需要從博客開始工作項目並獲取與他們相關的BlogComments。 – Cris

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 }