【问题标题】:select field from dictionary table using join in Linq使用 Linq 中的连接从字典表中选择字段
【发布时间】:2012-11-22 07:41:24
【问题描述】:

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

我想从详细信息表中查询一些字段,这些字段返回具有所有相同标题 ID 的多行。

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

例子

主表: ID 主名 日期 ...

详细信息表 ID 主ID 钥匙 价值

伪代码: 来自 context.mastertable 中的 master 在 context.detailstable 中加入详细信息 在 master.ID == detail.masterID 选择新的自定义类{ ID = master.ID, 名称 = master.MasterName Customfield = (detailsvalue.where key == "customfield") + (detailvalue.where key == "customfield2") };

希望有人可以帮助我。

格茨·卢克·克里宁

【问题讨论】:

    标签: linq entity-framework-4


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      这样的东西不行吗?:

      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
                  };
      

      如果没有,请详细说明您要查找的内容。 IE。描述您的数据是如何存储的,以及您希望从该查询中得到的最终结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-12
        • 2010-11-15
        • 1970-01-01
        • 2012-06-05
        相关资源
        最近更新 更多