2012-11-21 37 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