【问题标题】:C# linq Perform join with default value if join returns nullC# linq 如果连接返回 null,则使用默认值执行连接
【发布时间】:2018-02-20 17:37:38
【问题描述】:

我正在尝试执行连接,如果连接返回 null,我想要默认值。

我的代码是:

MyVar = from parent in db.ParentTable
        join child1 in db.Child1 on parent.Id equals child1.ParentId into j1

        select new ParentClass
        {
          Id = Parent.Id,
          Name = Parent.Name,
          Children = from child1 in db.Child1
                     join rm in db.Table1 on Child1.ID equals rm.ChildId
                     where Child1.ParentId == parent.Id && rm.OperationId == Op.ID
                     select new Child
                     {
                      Name = child1.Name,
                      ID = child1.ID,
                      Flag = rm.Value
                     }
        }
        }).FirstOrDefault();

数据库的结构是: 父表:

Id | Name
1  | A
2  | B

Child1 表:

ParentId | Id | Name
1        | 21 | A1
1        | 22 | A2
2        | 23 | A3
1        | 24 | A4

表 1:

Id | Child1Id | Value | OpID
1  | 21       | False | 123
2  | 21       | False | 124
3  | 21       | true  | 125
4  | 22       | true  | 126

等等..

注意:Child1 中的多个条目可以有相同的 Parent,Table1 中的多个条目可以有相同的 Child1Id。

问题:如果儿童的加入返回空,我想像这样显示我的自定义对象:

{
  Name = child1.Name,
  ID =   child1.ID,
  Flag = False
 }

如果 join 返回空数组并且应该有 child1.Name 和 ID,则这必须是默认对象。我如何做到这一点?

【问题讨论】:

标签: c# mysql linq join


【解决方案1】:

您需要使用left join,并且除了添加到加入条件之外还需要Op.ID 的where 类:

Children = from child1 in db.Child1
           where child1.ParentId == parent.Id
           join rm in db.Table1 on new { child1.ID, OpId = Op.ID } equals new { rm.ChildId, rm.OperationId } into joint
           from rm in joint.DefaultIfEmpty()
           select new Child
           {
               Name = child1.Name,
               ID = child1.ID,
               Flag = rm == null ? false : rm.Value
           }

【讨论】:

  • 感谢您的回复,它在Op.ID 上给出了语法错误,在'join rm in db.Table1 on new { child1.ID, Op.ID }' 说,An anonymous type cannot have multiple properties with the same name
  • @thewarri0r9 - 查看更新。没注意到名字是一样的
  • 你先生真棒!谢谢
  • @thewarri0r9 - 很高兴它有帮助:)
猜你喜欢
  • 1970-01-01
  • 2017-01-01
  • 1970-01-01
  • 2020-04-12
  • 2013-05-12
  • 1970-01-01
  • 2012-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多