我遇到了EF6延遲加載的問題。我搜索了StackOverflow,但我發現的其他問題不適合我的情況。EF6不會延遲加載導航屬性
我使用的是virtual
關鍵字,我的課程是public
。 LazyLoadingEnabled
和ProxyCreationEnabled
都設置爲true
。
當我從分貝加載course
對象,presentationId
被設置爲正確的id
和presentation
是null
這是正確的,因爲它尚未裝載。
當我通過presentation
屬性爲PresentationsController.ToDto()
方法應該是懶加載,但我得到的方法內null reference
例外,因爲它仍然null
。
我知道,關係工作,因爲當我強迫與它被加載的public static CourseDto ToDto(Course item, DnbContext db)
方法一個破發點加載course
在Watch window
的presentation
財產。見圖片:
正如你可以看到item.presentation
是null
:
當我手動評估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; }
}
我的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;
}
任何想法?
上帝保佑你!謝謝! –