EF6 doesn't have lazy navigation navigation

I have a problem with lazy loading EF6. I was looking for StackOverflow, but other questions that I found are not relevant to my case.

I use the keyword virtualinstead of my classes public. LazyLoadingEnabledand ProxyCreationEnabledset to true.

When I load an object coursefrom db, it is presentationIdset to correct idand presentationis null, which is correct because it is not loaded yet.

When I pass a property to a presentationmethod PresentationsController.ToDto(), it should be lazy, but I get an exception null referenceinside the method because it is still there null.

I know that the relationships work, because when I forcibly load the property presentationa courseto Watch windowa point by the method of interruption public static CourseDto ToDto(Course item, DnbContext db), it is loaded. See images:

As you can see, item.presentationthere are null:

enter image description here

When I manually evaluate db.courses.Find(257).presentation, which refers to the same presentation as the object item, they both load:

enter image description here

Here are my POCOs:

public abstract class BaseModel : ISoftDelete {
    public int id { get; set; }
}

public class Course : BaseModel {
    [Required]
    public int presentationId { get; set; }
    public virtual Presentation presentation { get; set; }
}

My methods for managing the Web API are:

// GET api/Courses/5
public CourseDto GetCourse(int id) {
    var item = db.courses.FirstOrDefault(x => x.id == id);
    return ToDto(item, db);
}

public static CourseDto ToDto(Course item, DnbContext db) {
    var dto = new CourseDto();

    if (item.presentationId > 0) dto.presentation = PresentationsController.ToDto(item.presentation, db);

    return dto;
}

Any ideas?

+4
source share
1 answer

Entities must explicitly declare public constructors if you want to use lazy loading through dynamic proxies. (If you have other options)

public abstract class BaseModel : ISoftDelete {
    public BaseModel() { }
    public int id { get; set; }
}

public class Course : BaseModel {
    public Course() { }
    [Required]
    public int presentationId { get; set; }
    public virtual Presentation presentation { get; set; }
}
+7
source

Source: https://habr.com/ru/post/1530213/


All Articles