EF6 不延迟加载导航属性

EF6 does not lazy load navigation property(EF6 不延迟加载导航属性)

本文介绍了EF6 不延迟加载导航属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having an issue with EF6 lazy loading. I've searched StackOverflow, but the other questions I've found doesn't fit my case.

我正在使用 virtual 关键字,并且我的类是 public.LazyLoadingEnabledProxyCreationEnabled 都设置为 true.

I'm using the virtual keyword and my classes are public. LazyLoadingEnabled and ProxyCreationEnabled are both set to true.

当我从数据库加载 course 对象时,presentationId 被设置为正确的 idpresentationnull 是正确的,因为它还没有被加载.

When I load a course object from the db, presentationId is set to the correct id and presentation is null which is correct, because it hasn't been loaded yet.

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

When I pass the presentation property to the PresentationsController.ToDto() method it should be lazy loaded, but I get a null reference exception inside the method because it's still null.

我知道这些关系正在起作用,因为当我在 Watch window 中强制加载 coursepresentation 属性时,会出现断点在 public static CourseDto ToDto(Course item, DnbContext db) 方法中,它被加载.查看图片:

I know that the relationships are working because when I force load the presentation property of a course in the Watch window with a break point at the public static CourseDto ToDto(Course item, DnbContext db) method it gets loaded. See images:

你可以看到 item.presentationnull:

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

When I manually evaluate db.courses.Find(257).presentation which is referencing the same presentation as the item object does, they're both loaded:

这是我的 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 控制器方法:

My Web API controller methods:

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

有什么想法吗?

推荐答案

如果你想通过动态代理使用延迟加载,实体必须明确声明公共构造函数.(如果你有其他带参数的)

Entities must have explicitly declared public constructors if you want to use lazy loading via dynamic proxies. (If you have other with parameters)

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

这篇关于EF6 不延迟加载导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:EF6 不延迟加载导航属性