2012-11-21 34 views
0

我有2個數據庫表。一個帶有Master Recors,另一個帶有使用字典結構的詳細記錄。從字典表中選擇字段使用Linq聯接

我想從detailstable查詢一些字段,這是返回具有所有相同標題ID的多個行。

有沒有辦法使用LINQ加入兩個表

例如創建一個自定義記錄

主表: ID MasterName 日期 ...

細節表 ID MasterID Key Value

僞代碼: 從主在context.mastertable 加入詳細context.detailstable 上master.ID == detail.masterID 選擇新CustomClass { ID = master.ID, 名稱= master.MasterName 的CustomField =( detailsvalue.where key ==「customfield」)+(detailvalue.where key ==「customfield2」) };

希望有人能幫助我。

grtz Luuk Krijnen

回答

0

會不會像這樣工作?:

var query = from master in context.masterTable 
      join detail in context.detailTable 
      on master.Id == detail.masterId 
      where detail.Key == "customField" || detail.Key == "customField2" 
      select new 
      { 
       id = master.Id, 
       name = master.Name, 
       customField = detail.Key 
      }; 

如果沒有,精心製作多一點上究竟你要尋找的。 I.E.描述你的數據是如何存儲的以及你希望從這個查詢中獲得的最終結果。

1

您可以使用在Join()方法中創建的匿名類型。

List<Master> list1 = new List<Master>(){ 
    new Master(){ Id=1, Name="Name1"}, 
    new Master(){ Id=2, Name="Name2"}}; 

    List<Detail> list2 = new List<Detail>(){ 
    new Detail(){ Id=1, MasterId=1, Description="Description1"}, 
    new Detail(){ Id=2, MasterId=1, Description="Description2"}, 
    new Detail(){ Id=3, MasterId=1, Description="Description3"}, 
    new Detail(){ Id=4, MasterId=2, Description="Description4"}, 
    new Detail(){ Id=5, MasterId=2, Description="Description5"}}; 

    // IEnumerable of anonymous types 
    var result = list1.Join(list2, m => m.Id, d => d.MasterId, (m, d) => new { Id = m.Id, Name = m.Name, Description = d.Description }); 

    foreach (var item in result) 
    Console.WriteLine(item.Id + " " + item.Name + " " + item.Description + Environment.NewLine); 

    // Returns 
    // 1 Name1 Description1 
    // 1 Name1 Description2 
    // 1 Name1 Description3 
    // 2 Name2 Description4 
    // 2 Name2 Description5