尝试使用SingleOrDefault

时间:2016-06-30 00:05:21

标签: c# ef-code-first

我有这个查询,它是从2个实体加入

.GroupJoin(uow.Airports.List(),fbm=>fbm.FlyBillMains.AirPortId_Arrival,arr=>arr.AirPortId,(fbm,arr)=>new FlyBillMainDetails
                   {
                       BranchName = fbm.BranchName,
                       CompanyCode = fbm.CompanyCode,
                       CompanyName = fbm.CompanyName,
                       CustomerName = fbm.CustomerName,
                       FlyBillMains = fbm.FlyBillMains,
                       PayTypeName = fbm.PayTypeName,
                       PolicyCode = fbm.PolicyCode,
                       CountryName = fbm.CountryName,
                       AirportNameArrival=arr.SingleOrDefault().Name,
                       Address = fbm.Address,
                       ShipperName = fbm.ShipperName,
                       ShipperAddress = fbm.ShipperAddress,
                       ShipperPhone = fbm.ShipperPhone,
                       ConsigeeName = fbm.ConsigeeName,
                       ConsigeeAddress = fbm.ConsigeeAddress,
                       ConsigeePhone = fbm.ConsigeePhone
                   })

在这一行

AirportNameArrival=arr.SingleOrDefault().Name

如果AirportNameArrival为null,我得到了空引用 知道AirportNameArrival是字符串

1 个答案:

答案 0 :(得分:2)

您可以使用Null-conditional Operator ?.

string AirportNameArrival = arr.SingleOrDefault()?.Name;

默认情况下,您还可以将其与Null-coalescing operator ??结合使用以获取空字符串:

string AirportNameArrival = arr.SingleOrDefault()?.Name??"";