简体   繁体   中英

Entity Framework 6: no lazy loading on one-to-one relationship

I am using code first to an existing database, and i am having some trouble getting one of my navigation properties to lazy load. Namely the only one-to-one relationship in my codebase.

The entityes look like this:

public abstract class DomainObject<T>
{
    /// <summary>
    /// The Id of this object.
    /// </summary>
    [Key]
    public T Id { get; set; }
}

[Table("Ordre")]
public class KundeOrdre : DomainObject<int>
{
    //normal properties above
    public virtual Bestilling Bestilling { get; set; }
    //Various methods and other navigational properties below
}


[Table("Bestilling")]
public class Bestilling : DomainObject<int>
{
    //normal properties above
    public virtual KundeOrdre KundeOrdre { get; private set; }
    //Various methods and other navigational properties below
}

And their fluent mapping looks like this:

 modelBuilder.Entity<KundeOrdre>()
             .HasRequired<Bestilling>(x => x.Bestilling)
             .WithRequiredPrincipal(x => x.KundeOrdre)
             .Map(x => x.MapKey(OrderFK));

If i eager load bestilling this seems to work as intended, but if i try to lazy load it i get back an object where all properties are null or default values.

I found a design fault in our code, the bestilling navigation property was being instantiated in the constructor. Removing that line fixed all of my issues in a single stroke.

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