我正在尝试使用lambda表达式连接三个表。如果两个表必须相互匹配,则下面的代码有效,但是如果存在与其他表不对应的记录,则会返回错误。Object reference not set to an instance of an object.
using (WeeklyCreditEntities WCE = new WeeklyCreditEntities())
{
var xx = Raw.GroupJoin(WCE.tblCHRIS,
a => a.CHRISID,
b => b.CHRISID,
(a, b) => new
{
raw = a,
chris = b.DefaultIfEmpty().FirstOrDefault()
}).Select(x => new
{
RawEMpid = x.raw.EmployeeID,
CHRISEmpID = x.chris.EmployeeID,
RawCHRISID = x.raw.CHRISID,
RawFullname = x.raw.Fullname,
RawAmount = x.raw.Amount,
chrisBank = x.chris.BankAccount
}).ToList();
答案 0 :(得分:2)
您可以将安全导航运算符与null-coalescing运算符一起使用:
using (WeeklyCreditEntities WCE = new WeeklyCreditEntities())
{
var xx = Raw.GroupJoin(WCE.tblCHRIS,
a => a.CHRISID,
b => b.CHRISID,
(a, b) => new
{
raw = a,
chris = b.DefaultIfEmpty().FirstOrDefault()
}).Select(x => new
{
RawEMpid = x.raw?.EmployeeID ?? defaultValue,
CHRISEmpID = x.chris?.EmployeeID ?? defaultValue,
RawCHRISID = x.raw?.CHRISID ?? defaultValue,
RawFullname = x.raw?.Fullname ?? defaultValue,
RawAmount = x.raw?.Amount ?? defaultValue,
chrisBank = x.chris?.BankAccount ?? defaultValue
}).ToList();
或者,如果您使用的是旧版本的C#/ Visual Studio,则可以使用三元运算符:
using (WeeklyCreditEntities WCE = new WeeklyCreditEntities())
{
var xx = Raw.GroupJoin(WCE.tblCHRIS,
a => a.CHRISID,
b => b.CHRISID,
(a, b) => new
{
raw = a,
chris = b.DefaultIfEmpty().FirstOrDefault()
}).Select(x => new
{
RawEMpid = x.raw != null? x.raw.EmployeeID : defaultValue,
CHRISEmpID = x.chris != null? x.chris.EmployeeID : defaultValue,
RawCHRISID = x.raw != null? x.raw.CHRISID : defaultValue,
RawFullname = x.raw != null? x.raw.Fullname : defaultValue,
RawAmount = x.raw != null? x.raw.Amount : defaultValue,
chrisBank = x.chris != null?x.chris.BankAccount : defaultValue
}).ToList();