簡體   English   中英

導航屬性未在延遲加載中加載

[英]Navigation properties not loading in Lazy Load

我創建了這兩個類(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 ...相關的地址被加載!

當我使用GetAllAddressesCityId具有值,但City始終為null。

ProxyCreationEnabledLazyLoadingEnabled是“真”。

為什么我在“地址”課程上時,城市沒有加載?

HasRequired方法之后使用WithRequiredPrincipalWithRequiredDependent

看看實體框架文檔

在大多數情況下,實體框架可以推斷出哪種類型是從屬類型以及哪種是關系中的主體。 但是,當關系的兩端都是必需的,或者雙方都是可選的時,實體框架就無法識別依賴項和主體。 當需要關系的兩端時,請在HasRequired方法之后使用WithRequiredPrincipal或WithRequiredDependent。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM