EF6不会延迟加载导航属性

Hei*_*tad 4 c# entity-framework-6

我遇到了EF6延迟加载的问题.我搜索过StackOverflow,但我发现的其他问题并不适合我的情况.

我正在使用virtual关键字,我的课程是public.LazyLoadingEnabled并且ProxyCreationEnabled都被设置为true.

当我打开一个course从数据库对象,presentationId被设置为正确id并且presentationnull这是正确的,因为它没有被加载.

当我将presentation属性传递给PresentationsController.ToDto()方法时,它应该是延迟加载的,但是我null reference在方法中得到一个异常,因为它仍然存在null.

我知道关系正在起作用,因为当我强制加载a的presentation属性时,course在加载方法Watch window的断点处public static CourseDto ToDto(Course item, DnbContext db).看图像:

正如你看到的item.presentationnull:

在此输入图像描述

当我手动评估db.courses.Find(257).presentation哪个引用与item对象相同的表示时,它们都被加载:

在此输入图像描述

这是我的POCO:

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; }
}
Run Code Online (Sandbox Code Playgroud)

我的Web API控制器方法:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Mar*_*rio 7

如果要通过动态代理使用延迟加载,则实体必须已显式声明公共构造函数.(如果你有其他参数)

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; }
}
Run Code Online (Sandbox Code Playgroud)