[英]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.