[英]Entity Framework : Eager loading not working with string foreign key
我在使用緊急加載來加載子實體時遇到了麻煩,該緊急加載在項目中的其他任何地方都可以正常工作,但是不能與任何字符串外鍵一起使用。 我的模型是:
public class Listing : BaseAudit<int>
{
public int? CommunityId { get; set; }
public string LotId { get; set; }
public Lot Lot { get; set; }
}
public class Lot : BaseAudit<string>
{
public ICollection<Listing> Listings { get; set; }
}
public class BaseAudit<T> : BaseId<T>
{
public BaseAudit()
{
CreatedDate = DateTime.Now;
}
public DateTime? CreatedDate { get; set; }
public string CreatedBy { get; set; }
public DateTime? UpdatedDate { get; set; }
public string UpdatedBy { get; set; }
}
public class BaseModel
{
public BaseModel()
{
Active = true;
}
public bool Active { get; set; }
}
public class BaseId<T> : BaseModel
{
public T Id { get; set; }
}
我正在嘗試加載我嘗試過的Listing
Lot
屬性:
_db.Listings.Where(m => m.CommunityId == communityId && m.LotId != null).Include(a => a.Lot).ToList();
我已經檢查過它通過使用斷點來生成正確的SQL,但它總是返回所有Lot
屬性為null。 我無法弄清楚我在做什么錯。
簡短的答案: Listings
應該是一個虛擬集合; LotId
永遠不會為null,並且Include
應該緊接在DbSet之后。 您可能應該為繼承策略建模
長答案似乎您嘗試在Lots
和Listings
之間配置一對多關系:每個Lot
具有零個或多個Listings
,每個Listing
恰好屬於一個Lot
。
對於一對多的人,您應該聲明您的清單虛擬清單
public virtual ICollection<Listing> Listings { get; set; }
由於一對多關系,沒有Lot
就沒有Listing
,因此,批次的主鍵LotId
的外鍵永遠不會為空。
所以,你有一個可空INT communityId
(這是真的,或者communityId一個int?),並且希望所有Listings
具有相同的價值Listing.CommunityId inclusive the one and only
地段this
Listing`有:
using System.Data.Entity;
List<Listing> result = dbContext.Listings
.Include(listing => listing.Lot)
.Where(listing => listing.communityId == communityId)
.ToList();
如果這樣做沒有幫助,則您對繼承的使用可能會引起問題。 關系數據庫不知道繼承的概念。 您應該使用流利的API(或屬性)告訴實體框架將哪種繼承策略建模到表中。 請參閱繼承策略
最后,我看到一些主鍵是int,一些主鍵是字符串。 那是真的嗎? 它有用嗎?
EF6不支持在相關實體上的“ Include
在Where
”。
可能的解決方法: 實體框架:篩選相關的實體集合
從Entity Framework 6開始,沒有一種方法可以過濾使用.Include()時加載了哪些相關實體。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.