2013-04-16 80 views
2

我有兩個表。這些表格之間存在一對多關係。我要選擇公司表格和BankAccount列表表格(適用於公司ID)。 我怎麼用Linq-to-Sql來做到這一點?用Linq to Sql選擇多個表

public class Company 
{ 
    // My Fields 
    [Key] 
    public Guid ID { get; set; } 


    public string FullName { get; set; } 

    // My virtual properties FOR relationships(one-to-one,one-to-many etc.). 


    public virtual List<BankAccount> BankAccounts { get; set; } 
} 

public class BankAccount 
{ 

    // My Fields 
    //[ScaffoldColumn(false)] 
    [Key] 
    public Guid ID { get; set; } 

    [ForeignKey("Companies")] 
    public Nullable<Guid> CompanyID { get; set; } 

    public string BankName { get; set; } 




    // My virtual properties FOR relationships(one-to-one,one-to-many etc.). 

    public virtual Company Company { get; set; } 
} 

我寫這篇文章如下,但我不喜歡它

List<List<BankAccount>> bankaccounts = new List<List<BankAccount>>(); 
foreach (var comp in companyRepository.Companies) 
{ 
     List<BankAccount> banks = new List<BankAccount>(); 
     foreach (var bank in bankRepository.BankAccounts) 
     { 
      if (comp.ID == bank.CompanyID) 
      { 
       banks.Add(bank); 
      } 
     } 
     bankaccounts.Add(banks); 
     banks = new List<BankAccount>(); 
} 
+0

你試過了什麼? –

回答

2

我認爲有以下將產生相同的結果。

var bankaccounts = companyRepository.Companies.Select(c => c.BankAccounts) 
         .ToList(); 

如果您正在使用實體框架,您可以提前加載'BankAccounts'屬性以最小化數據庫調用。

希望這會有所幫助。

+0

謝謝@ shakib。太好了。現在它工作正常。 –

+0

不客氣。如果它適合你,你能否將答案標記爲已接受。 :) – shakib

+0

OK :))我做到了。 –