我有两个参与亲子关系的课程。父类为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();
我得到所有孩子,但没有父母数据。
答案 0 :(得分:1)
如果您正在使用Entity Framework,则可以在加载对象时使用.Include()
来获取导航属性数据。请注意,它往往会产生一些非常粗糙的查询。
var city = (
from c in db.Cities.Include(c => c.Country)
where c.CountryId == CountryId
orderby c.Name
select c
).ToList();