我在从数据库中提取模型时试图加载属性。问题来自于试图在扩展类上加载特定模型。
我的模型结构是Jobs包含一个JobItems列表。 JobItems是一个抽象类,它扩展为4种不同类型的JobItem,其中一些包含其他表(如产品和供应商)的外键。
我目前的代码:
return db.Jobs
.Include(m => m.Items)
.Include(m => m.Items.Select(j => j.PickUpAddress))
.Include(m => m.Items.OfType<BulkJobItem>().Select(j => j.Product))
.Include(m => m.Items.OfType<BulkJobItem>().Select(j => j.Supplier))
.Include(m => m.Items.OfType<StockJobItem>().Select(j => j.Product))
.Include(m => m.Items.Select(j => j.DropOffAddress))
.Include(m => m.Client);
probem代码是.OfType()
的包含,它给出了以下错误:
System.ArgumentException: 'The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.'
作为一项解决方案,我目前已经这样做了:
IQuerable<Job> jobs = db.Jobs
.Include(m => m.Items)
.Include(m => m.Items.Select(j => j.PickUpAddress))
.Include(m => m.Items.Select(j => j.DropOffAddress))
.Include(m => m.Client);
EagerLoadNavigationProperties(jobs.SelectMany(m => m.Items));
return jobs;
方法:
private void EagerLoadNavigationProperties(IEnumerable<JobItem> items)
{
foreach (BulkJobItem item in items.OfType<BulkJobItem>())
{
db.Entry(item).Reference(m => m.Product).Load();
db.Entry(item).Reference(m => m.Supplier).Load();
}
foreach (StockJobItem item in items.OfType<StockJobItem>())
{
db.Entry(item).Reference(m => m.Product).Load();
}
}
我觉得这个解决方案不干净或效率最高,但现在在测试阶段仍然有效。