【问题标题】:c# Linq Chain with avoid null exeptionc# Linq Chain 避免空异常
【发布时间】:2019-10-13 09:25:03
【问题描述】:

我有多个表,具有一对多关系,如链

1- 地址有邮政编码

2- 邮政表有区域 id

3-区域表有城市ID

4- 城市表有县 id

5- 县表有国家 ID

6- 并在最后一个国家/地区表中

我需要从每张表中获取街道名称、完整的邮政编码、地区名称、城市名称、县名、国家/地区名称

查询如下

var address = from add in _Database.Addresses
                      select add;

        address.Select(x=>new AddressClass { 
        BuildingNameOrNumber=x.BuildingNameOrNumber,
        MainStreet = x.Postcode ==null ? string.Empty: x.Postcode.StreetName,
        FullPostCode = x.Postcode == null ?  string.Empty :x.Postcode.FullPostcode,
        AreaName = x.Postcode == null ? string.Empty : x.Postcode.Area == null ? string.Empty: x.Postcode.Area.Name,
        CityName = x.Postcode == null ? string.Empty : x.Postcode.Area == null ? string.Empty : x.Postcode.Area.City == null ? string.Empty:  x.Postcode.Area.City.Name,
        CountyName = x.Postcode == null ? string.Empty : x.Postcode.Area == null ? string.Empty : x.Postcode.Area.City == null ? string.Empty : x.Postcode.Area.City.County == null ?string.Empty: x.Postcode.Area.City.County.Name,
        CountryName= x.Postcode == null ? string.Empty : x.Postcode.Area == null ? string.Empty : x.Postcode.Area.City == null ? string.Empty : x.Postcode.Area.City.County == null ? string.Empty : x.Postcode.Area.City.County.Country == null ? string.Empty:x.Postcode.Area.City.County.Country.CountryName
        })

我需要将这个多重条件替换为每个属性的一个条件

【问题讨论】:

    标签: c# entity-framework linq


    【解决方案1】:

    这对我来说太复杂了,抱歉:)

    但您需要的是 ??? 运算符。您真正复杂的查询中的倒数第二项将类似于:

    CountyName = x.Postcode?.Area?.City?.County?.Name ?? string.Empty
    

    x?.y 如果x 不是null,则返回y,否则返回null。如果y 不是nullable,那么x?.y 的结果将变为Nullable<T>,其中Ttypeof(y)

    x ?? y 如果x 不是null,则返回x,如果是,则返回yxy 的类型在这里应该相同。 希望对你有帮助

    编辑

    在第二个外观中,我看到您正在使用带有 IQueryable 的 LINQ,它不能使用 null 传播运算符。因此,在这种情况下,您没有此选项,您可以使用ToList() 加载所有数据,如果数据量很小,则对它们运行查询。或者您可以在单独的查询中加载每个部分(由于我不推荐子元素的数量)。或者,您可以使用this等工具

    我的建议是第一个选项,但在大型数据集上可能对内存不友好。

    很抱歉最初的仓促回答。 ?

    【讨论】:

    • 异常:- 表达式树 lambda 可能不包含空传播运算符 CountryName = x.Postcode?.Area?.City?.County?.Country?.CountryName ?? string.Empty
    猜你喜欢
    • 1970-01-01
    • 2010-09-29
    • 2011-10-01
    • 2021-04-25
    • 2015-11-25
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    相关资源
    最近更新 更多