【发布时间】:2014-11-03 13:54:13
【问题描述】:
我已经创建了这两个类 (POCO)...
public class Address
{
public int Id { get; set; }
public string Street { get; set; }
public string Number { get; set; }
public string Neighborhood { get; set; }
public string ZipCode { get; set; }
public int CityId { get; set; }
public virtual City City { get; set; }
}
public class City
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
...然后我映射...
public class AddressMap : EntityTypeConfiguration<Address>
{
public AddressMap()
{
ToTable("Address");
HasKey(p => p.Id);
...
...
HasRequired(p => p.City)
.WithMany(p => p.Addresses)
.HasForeignKey(p => p.CityId);
}
}
public class CityMap : EntityTypeConfiguration<City>
{
public CityMap()
{
ToTable("City");
HasKey(p => p.Id);
...
...
HasMany(p => p.Addresses)
.WithRequired(p => p.City)
.HasForeignKey(p => p.CityId);
}
}
然后我用两个方法创建一个类:
-
FindCityById返回一个城市及其各自的地址...Context.Cities.Find(key)和 -
GetAllAddresses(仅用于测试目的)Context.Addresses.ToList()
当我使用FindCityById...相关地址被加载!
当我使用GetAllAddresses 时,CityId 有值,但 City 始终为 null。
ProxyCreationEnabled 和 LazyLoadingEnabled 是“真”。
为什么当我在地址类中时城市没有加载?
【问题讨论】:
-
不加载是什么意思,因为是懒加载,所以当你试图访问集合中的地址时就会加载。
-
我在这里找到了答案stackoverflow.com/questions/22194266/… EF 需要显式声明构造函数。
标签: c# entity-framework lazy-loading poco