我先用EF6代碼,但似乎無法得到惰性加載工作。急切的加載工作正常。我有以下類:EF代碼第一懶惰加載不工作
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
。我懷疑這是造成這個問題的原因。
不回答你的問題,但它的糟糕的設計使用基礎實體類,http://msdn.microsoft.com/en-us/magazine/jj553510.aspx –
我猜這可能是因爲你使用OFType ,你怎麼不直接從上下文訪問商家,而是通過用戶瀏覽 –
我看到了作者對基本實體類的看法,但EF中的默認設置實際上將這些屬性映射到派生表中,而不是一個單獨的BaseEntity表,因此性能不受影響。我並不認爲他的概念論證很強大,我需要一些像DateAdded和DateUpdated這樣的更改跟蹤信息,所以基類使這更容易 – user1032657