pdlist = (from a in context.EMPLOYEES
join b in context.PERSONS on a.PERSON_ID equals b.PERSON_ID
where a.SUPERVISOR_ID == empId
select new Pollidut.Models.Pollidut
{
PollidutId = a.EMPLOYEE_ID,
PollidutName = b.PERSON_NAME,
DistributionHouseId = a.DISTRIBUTION_HOUSE_ID == null ? 0 : (int)a.DISTRIBUTION_HOUSE_ID
}).ToList();
DateTime dt = DateTime.Now.Date;
var pdTargets = (from p in context.PALLYDUT_TARGET
where p.Active == true && p.StartDate <= dt && p.EndDate >= dt
group p by p.PallydutId into g
select new
{
PollidutId = g.Key,
Start = g.Select(x => x.StartDate).Min(),
End = g.Select(y => y.EndDate).Max(),
Target = g.Select(z => z.Target).Sum()
}).ToList();
var PdTargetsList = (from m in pdlist
join n in pdTargets on m.PollidutId equals n.PollidutId into t
from l in t.DefaultIfEmpty()
select new
{
PallydutId = m.PollidutId,
PallydutName = m.PollidutName,
DistributionId = m.DistributionHouseId,
StartDate = l.Start == null ? dt : l.Start,
EndDate = l.End == null ? dt : l.End,
Target = l.Target == null ? 0 : l.Target
}).ToList();
pdlist
是pdTarget可以设置或不设置的员工列表。 pdTarget
可以为空。当我使用pdTargets离开连接pdlist时,我得到了Object引用而没有设置错误。 pdTargets集合返回null。如何修复它。任何人都非常感谢我。
答案 0 :(得分:2)
我怀疑你获得Null reference exception
的原因是因为你正在直接访问空对象(在你的情况下是l
)的属性,即使你使用{{1}如果找不到匹配的行,则返回null的方法。您应该像这样更改您的代码: -
DefaultIfEmpty()
此外,如果您认为您的一个对象 select new
{
PallydutId = m.PollidutId,
PallydutName = m.PollidutName,
DistributionId = m.DistributionHouseId,
StartDate = l == null ? dt : l.Start,
EndDate = l == null ? dt : l.End,
Target = l == null ? 0 : l.Target
}).ToList();
可以为null,那么我认为它不是关于左连接或普通连接,您的代码将在任何一种情况下抛出异常。请检查this MSDN文档以处理查询表达式中的空值。