在 EF 中获取具有引用实体的实体

Getting entity with referenced entities in EF

我有一个名为 Study 的实体:

 public class Study
{
    public Study()
    {
        Tasks = new List<Task>();
    }

    [Key]
    public string StudyUid { get; set; }

    public virtual List<Task> Tasks { get; set; }
}

我使用工作单元设计模式,我想通过它的任务进行研究。

我什么都试过了。

我已经在存储库中尝试过 class:

  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>();

我什至只是为了实验而尝试,在任务中删除了虚拟这个词 属性。

所有结果 study.Tasks.Count = 0;

在 Db 中我可以看到有我使用的 StudyUid 的任务。

请分享您的任何见解。

任何 .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() returns 您应该枚举的查询。它本身不会更改调用它的查询。