gpt4 book ai didi

c# - Linq加入抛出异常

转载 作者:行者123 更新时间:2023-11-30 23:08:41 26 4
gpt4 key购买 nike

我正在尝试对多个表使用左连接在像现在一样引入另一个表(tb4)之前,它工作正常它正在抛出未设置的对象引用。

在引入 tb4 之前,我从较早的结果集中获得了 3 条记录,这些记录的 stateId = null。但是因为我在上次连接中使用了相同的 id(即 stateid),它在 aa 中变为 null,即(aa.StateId)。所以,它正在 throw 异常(exception)。我们可以在应用连接时处理这件事吗?如果连接键变为空,我们该如何处理。

from tb1 in this.table1  join tb2 in table2 on tb1.Id equals tb2.fkId into temptbl
from aa in temptbl.DefaultIfEmpty()
join tb3 in table3 on tb1.Id equals tb3.StudentId into studentInfo
from pp in studentInfo.DefaultIfEmpty()
join state in tb4 on aa.StateId equals state.StateId into statesTemp
from ss in statesTemp.DefaultIfEmpty()
select new MyModel
{
City = aa == null ? string.Empty : aa.City + ", ",
State = ss == null ? string.Empty : ss.State1,
PostalCode = aa == null ? string.Empty : aa.PostalCode,
studentid = pp.PeopleId
}).ToList()

最佳答案

问题是,当离开加入表 tb4 时,您正在访问 aaStateId 属性。但是 aa 本身是左连接的结果,因此可能为空。访问它的属性会抛出异常。

当您使用 C# 5.0 时,您应该:

join state in tb4 on (aa == null ? null : aa.StateId) equals state.StateId

对于 C# 6.0 和更新版本,您可以改用 ?. 空传播运算符。

关于c# - Linq加入抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46336788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com