[英]EF Code First Lazy loading Not Working
我首先使用EF6代碼,但似乎無法使延遲加載工作。 急切的裝載工作正常。 我有以下課程:
public class Merchant : User
{
...
public virtual ICollection<MerchantLocation> MerchantLocations { get; set; }
}
public class MerchantLocation : BaseEntity
{
...
public int MerchantId { get; set; }
public virtual Merchant Merchant { get; set; }
}
public class User : BaseEntity
{
...
}
public class BaseEntity
{
...
public int Id { get; set; }
}
我通過以下代碼測試我的延遲加載位置(失敗):
public void Test_Lazy_Loading() {
using (var context = new MyDbContext()) {
var merchant = context.Users.OfType<Merchant>.First();
merchant.MerchantLocations.ShouldNotBeNull(); // fails
}
}
然而,急切的加載工作正常:
public void Test_Eager_Loading() {
using (var context = new MyDbContext()) {
var merchant = context.Users.OfType<Merchant>.Include("MerchantLocations").First();
merchant.MerchantLocations.ShouldNotBeNull(); // passes
}
}
MerchantLocations
被標記為public virtual
因此我不確定問題是什么。 我還在我的DbContext
構造函數中添加了以下內容:
Configuration.LazyLoadingEnabled = true;
Configuration.ProxyCreationEnabled = true;
編輯:我還注意到在上述測試中返回的merchant
對象不是EF代理。 這是一個普通的Merchant
。 我懷疑這是導致問題的原因。
我意識到問題是Merchant類不符合代理生成的要求。 具體來說,我需要添加一個受保護的無參數構造函數。 我只有一個私人的。
另一個可能導致延遲加載失敗的事情是非虛擬的導航屬性 。 對於OP來說情況並非如此,但這個問題是谷歌的一個重要結果,所以它可能有所幫助。
另一個可能的原因是不存在的映射數據庫列 。 我很驚訝地看到打破延遲加載而不是拋出數據庫異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.