当前位置: 代码迷 >> C# >> 帮忙瞧一下去这样写EF+LINQ怎能不对
  详细解决方案

帮忙瞧一下去这样写EF+LINQ怎能不对

热度:286   发布时间:2016-04-28 08:41:24.0
帮忙看一下去这样写EF+LINQ怎能不对
            var data = from employee in contexthelper.BsEmployee
                       join position in 
                       (
                          from employee_position in contexthelper.Employee_Position.Where(n => n.IsDisabled == false)
                                         join
                                             position in contexthelper.Position on employee_position.PositionID equals position.PositionId
                                         select new
                                         {
                                             PositionName = position.PositionName,
                                             Employee_Id = employee_position.Employee_Id
                                         }
                       )
                           on employee.employee_id equals position.Employee_Id into leftjoin1
                       from position in leftjoin1.DefaultIfEmpty()
                       join dept in contexthelper.BsDept on employee.DeptId equals dept.DeptId into leftjoin2
                       from dept in leftjoin2.DefaultIfEmpty()
                       join duty in contexthelper.BsDuty.Where(n => n.worker_sign == false) on employee.f_duty_id equals duty.duty_id into leftjoin3
                       from duty in leftjoin3.DefaultIfEmpty()
                       join department in contexthelper.BsDepartment on employee.f_dpt_id equals department.dpt_id into leftjoin4
                       from department in leftjoin4.DefaultIfEmpty()
                       join subdpt in contexthelper.BsSubdpt on employee.f_subdpt_id equals subdpt.sub_id into leftjoin5
                       from subdpt in leftjoin5.DefaultIfEmpty()
                       where employee.f_leave_sign == false && employee.id > MaxID
                       select new EmployeeModel
                       {
                           ID = employee.id,
                           UserNo = employee.employee_id,
                           UserName = employee.f_per_name,
                           Dept = dept == null ? "" : dept.DeptName,
                           SubDept = subdpt == null ? "" : subdpt.sub_dptname,
                           Duty = duty == null ? "" : duty.duty_name,
                           Position = position == null ? "" : position.PositionName
                       };


提示 DbIsNullExpression 的参数必须引用基元类型或引用类型。
------解决思路----------------------
三目中的null判断对应的IsNull()只适用于字段,而不适用于左连接产生的对象
你的问题,应该通过
rom duty in leftjoin3.DefaultIfEmpty({new Duty {DeptName = ""})
其他的DefaultIfEmpty也是类似

然后最终的Select中直接Dept = dept.DeptName即可,不需要判断了,因为dept在关联为空时,结果中会自动使用new Duty {DeptName = ""}这个对象
------解决思路----------------------
.DefaultIfEmpty(null)对于引用类型跟.DefaultIfEmpty()没有区别
你必须手动构造一个对象作为无关联时的默认值
  相关解决方案