简体   繁体   中英

Navigation properties not loading in Lazy Load

I've create these two classes (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; }
}

... then I mapping...

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);
    }
}

Then I create a class with two methods:

  • FindCityById which returns a City and their respective addresses... Context.Cities.Find(key) and
  • GetAllAddresses (just for test purposes) Context.Addresses.ToList()

When I use FindCityById ... the addresses related are loaded!

When I use GetAllAddresses , the CityId has value but City is always null.

ProxyCreationEnabled and LazyLoadingEnabled are "true".

Why the City is not loading when I'm in Address class?

Use WithRequiredPrincipal or WithRequiredDependent after the HasRequired method.

Have a look at Entity Framework documentation

In most cases the Entity Framework can infer which type is the dependent and which is the principal in a relationship. However, when both ends of the relationship are required or both sides are optional the Entity Framework cannot identify the dependent and principal. When both ends of the relationship are required, use WithRequiredPrincipal or WithRequiredDependent after the HasRequired method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM