linq - 将数据转换为列表时,通用存储库上的 EF DbContext 未执行预期的包含
问题描述
我有一个我正在使用的通用/基础存储库,它包含用于访问我的数据库的不同方法。
这是一个示例:
public IQueryable<T> FindAll(string[] includedProperties = null)
{
var setContext = _context.Set<T>();
if (includedProperties != null)
{
foreach (var property in includedProperties)
{
setContext.Include(property);
}
}
return setContext;
}
我通过以下方式调用此方法:
var employees = _employeeRepository.FindAll(new string[] { "JobPosition", "Department", "EmployeeTeams", "EmployeeTeams.Team" })
当我对员工执行 ToList() 时,不包括预期的导航属性。
我尝试将其切换并执行以下操作:
var employees = _employeeRepository.FindAll().Include("JobPosition")
.Include("Department")
.Include("EmployeeTeams")
.Include("EmployeeTeams.Team")
并且执行 ToList() 包括指定的导航属性。
我想在我的通用存储库上使用我的方法。关于如何解决这个问题的任何想法?
注意:我还尝试通过表达式包含导航属性
(Expression<Func<T, object>> predicate[])
还是一样的结果。
解决方案
Include 返回IQueryable(或IIncludableQueryable,具体取决于您如何称呼它),因此您需要将它们一个接一个地添加。
像这样试试
foreach (var property in includedProperties)
{
setContext = setContext.Include(property);
}