我有一个名为Study的实体:
public class Study
{
public Study()
{
Tasks = new List<Task>();
}
[Key]
public string StudyUid { get; set; }
public virtual List<Task> Tasks { get; set; }
}
我使用工作单元设计模式,我想用它的任务来完成研究。
我已经尝试了一切。
我在存储库类中尝试过这个:
public IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate, string
includePath = null)
{
if (!string.IsNullOrEmpty(includePath))
{
DbSet.Include(includePath);
}
return DbSet.Where(predicate);
}
用以下方式调用它:
Study study = studyRepository.SearchFor(c => c.StudyUid ==
studyUid,"Tasks").FirstOrDefault<Study>();
我甚至尝试过实验,删除了task属性中的虚拟词。
所有结果都是study.Tasks.Count = 0;
在Db中我可以看到我使用的StudyUid有任务。
请分享您的任何见解。
答案 0 :(得分:1)
在构造查询后应添加.Include()
个调用,否则将忽略它们。你应该写
public IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate, string
includePath = null)
{
var query = DbSet.Where(predicate);
if (!string.IsNullOrEmpty(includePath))
{
query = query.Include(includePath);
}
return query;
}
您的问题也在于DbSet.Include(includePath)
而不是query = query.Include(includePath)
。 Include()
返回您应枚举的查询。就其本身而言,它并没有改变它所调用的查询。