2012-08-31 101 views
1

我在.net4.0中使用EF5.0,並且我有三個像這樣的多對多相關連接的實體:用ef代碼優先查詢三個(或多個)多對多相關實體

public class A 
    { 
     public int Id { get; set; } 
     public ICollection<B> Bs { get; set; } 
    } 
    public class B 
    { 
     public int Id { get; set; } 
     public ICollection<A> As { get; set; } 
     public ICollection<C> Cs { get; set; } 
    } 
    public class C 
    { 
     public int Id { get; set; } 
     public ICollection<B> Bs { get; set; } 
    } 

,這是我的映射代碼:

 HasMany(a => a.Bs).WithMany(b => b.As).Map(m => 
     { 
      m.ToTable("A_B"); 
     }); 

     HasMany(c => c.Bs).WithMany(b => b.Cs).Map(m => 
     { 
      m.ToTable("B_C"); 
     }); 

對於有一定情況下,我怎麼可能讓所有的B間接相關的銫?

我希望得到一個乾淨的SQL查詢,如:

select C.* from C 
join B_C on B_C.Cid = C.id 
join A_B on A_B.Bid = B_C.Bid 
join A on A.id = A_B.Aid 
where A.id = 1 

折軸我得到的SQL沒有給定結表中的實體類型? 我下面的代碼有一個很醜的SQL與嵌套查詢:

var res = Context.C.Where(
       c => c.Bs.SelectMany(b => b.As.Select(a => a.Id)) 
          .Contains(theA.Id) 
        ); 

請幫助我,謝謝了很多!

回答

0

我會嘗試此查詢:

var res = Context.C.Where(c => c.Bs.Any(b => b.As.Any(a => a.Id == theA.Id))); 
+0

感謝您的回覆,但此查詢使SQL比我更復雜......它會產生一個更嵌套查詢和多了一個「存在」。 – akara

相關問題