C# EF6不延迟加载导航属性

C# EF6不延迟加载导航属性,c#,entity-framework-6,C#,Entity Framework 6,我对EF6延迟加载有问题。我已经搜索了StackOverflow,但是我发现的其他问题不适合我的情况 我正在使用virtual关键字,我的类是publicLazyLoadingEnabled和ProxyCreationEnabled都设置为true 当我从db加载课程对象时,presentationId设置为正确的id,presentation为null,这是正确的,因为它尚未加载 当我将presentation属性传递给presentationcontroller.ToDto()方法时,它应该

我对EF6延迟加载有问题。我已经搜索了StackOverflow,但是我发现的其他问题不适合我的情况

我正在使用
virtual
关键字,我的类是
public
LazyLoadingEnabled
ProxyCreationEnabled
都设置为
true

当我从db加载
课程
对象时,
presentationId
设置为正确的
id
presentation
null
,这是正确的,因为它尚未加载

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

我知道这些关系正在发挥作用,因为当我在
观察窗口中强制加载
课程的
演示
属性
,并在
公共静态课程中设置一个断点,将其加载到ToDto(课程项,DnbContext db)
方法时,它会被加载。请参见图片:

正如您所看到的
项。演示文稿

当我手动评估
db.courses.Find(257).presentation
时,它们都被加载了:

这是我的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; }
}
我的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;
}

有什么想法吗?

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


上帝保佑你!非常感谢。
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; }
}