选择子对象时,父导航属性为“null”

本文关键字:属性 null 导航 对象 选择 | 更新日期: 2023-09-27 18:22:27

我有两个类参与父子关系。父类是Country,子类是City:

public partial class Country
{
    public Country()
    {
        this.Cities = new List<City>();
    }
    public int Id { get; set; }
    public string Name { get; set; }
    public string AlphaCodeTwo { get; set; }
    public string AlphaCodeThree { get; set; }
    public Nullable<int> NumericCode { get; set; }
    public string Capital { get; set; }
    public string Nationality { get; set; }
    public Nullable<decimal> CapitalArea { get; set; }
    public Nullable<decimal> CapitalPopulation { get; set; }
    public string Image { get; set; }
    public virtual List<City> Cities { get; set; }
}
public partial class City
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
    public Nullable<int> NumericCode { get; set; }
    public virtual Country Country { get; set; }
}

当我使用以下LINQ查询选择City对象时,父类的导航属性为null:

private List<Country> _Country;
var City = _Country.SelectMany(c => c.Cities).OrderBy(ci => ci.Name).ToList();

我得到了所有的孩子,但没有家长数据。

选择子对象时,父导航属性为“null”

如果使用实体框架,则可以在加载对象时使用.Include()获取导航属性数据。请注意,它往往会产生一些相当棘手的查询。

var city = (
    from c in db.Cities.Include(c => c.Country)
    where c.CountryId == CountryId
    orderby c.Name
    select c
).ToList();