【问题标题】:Navigation properties not loading in Lazy Load导航属性未在延迟加载中加载
【发布时间】: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


【解决方案1】:

在 HasRequired 方法之后使用 WithRequiredPrincipal 或 WithRequiredDependent。

看看Entity Framework documentation

在大多数情况下,实体框架可以推断出关系中的依赖类型和主体类型。但是,当关系的两端都是必需的或双方都是可选的时,实体框架无法识别依赖关系和主体。当需要关系的两端时,在 HasRequired 方法之后使用 WithRequiredPrincipal 或 WithRequiredDependent。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    相关资源
    最近更新 更多