2013-03-01 26 views
0

我有一組使用外鍵,像這樣使用LINQ to看看是否有任何一個子記錄有sepcific值

A 1----* B 

一個鏈接表,A可以有裏許多記錄。

我需要添加一個「where」子句來返回所有的A記錄,其中B.isMax == true如果某個標誌被傳遞給我的函數。我不知道如何處理這個。

public List<A> GetA(int AID, string AName, bool? isActive, bool? isMax) 
    { 
     var q = from a in Context.A 
       select a; 

     if (AID > 0) 
     { 
      q = q.Where(c => c.AID == AID); 
     } 

     if (!string.IsNullOrEmpty(AName)) 
     { 
      q = q.Where(c => c.Name.Contains(AName)); 
     } 

     if (isActive != null) 
     { 
      q = q.Where(c => c.IsActive == isActive); 
     } 

     if (isMax != null) 
     { 
      // ???? Can't do this. How can I implement this kind of thing?? 
      q = q.Where(c => c.B.IsMax == isMax); 
     } 

     List<A> ret = q.ToList(); 

     return ret; 
    } 

任何想法??

+0

根據您的要求,它既可以是「Any」,也可以是「All」。另外,當你引用一個嵌套集合時,可能會推薦使用'q = q.Include(「B」)。其中(c => c.Any/All(x => x.IsMax == isMax)) '以避免進一步的N + 1問題。 :) – 2013-03-01 17:34:48

回答

2

您可以使用Any

q = q.Where(c => c.B.Any(i => i.IsMax == isMax)); 

Any用於檢查序列中的任何元素是否滿足條件

1

你的意思是Any

q = q.Where(c => c.B.Any(b => b.IsMax == isMax)); 
0

你覺得,這是個好主意嗎?

public List<A> GetA(int AID, string AName, bool? isActive, bool? isMax) 
{ 
    return Context.A 
      .Where(c => 
         (AID <= 0 || c.AID == AID) 
        && (string.IsNullOrEmpty(AName) || c.Name.Contains(AName)) 
        && (isActive == null || c.IsActive == isActive) 
        && (isMax == null || c.B.Any(b => IsMax == isMax)) 
       ) 
      .ToList(); 
} 
相關問題