使用Linq中的连接从字典表中选择字段

时间:2012-11-21 22:09:44

标签: linq entity-framework-4

我有2个数据库表。一个使用Master Recors,另一个使用字典结构的详细记录。

我想查询detailstable中的一些字段,这些字段返回多行,所有行具有相同的标题ID。

有没有办法使用连接两个表的linq创建自定义记录

例如

主表: ID MasterName 日期 ...

详细信息表 ID MasterID 键 值

psuedo代码:      来自master中的context.mastertable      加入context.detailstable中的详细信息      在master.ID == detail.masterID上      SELECT new CustomClass {          ID = master.ID,          Name = master.MasterName          Customfield =(detailsvalue.where key ==“customfield”)+(detailvalue.where key ==“customfield2”)          };

希望有人可以帮助我。

grtz Luuk Krijnen

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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.描述您的数据的存储方式以及您希望从此查询中获得的最终结果。