实体框架Include()返回null导航属性

时间:2015-11-22 07:52:21

标签: c# asp.net-mvc entity-framework entity-framework-6

我遇到Include功能问题。我有一个Team类,其Owner属性为Owner。我有一个辅助函数,它包含我的EF调用,如下所示;

public Task<List<T>> GetManyAsync(
    Expression<Func<T, bool>> filter = null,
    Expression<Func<T, object>> includeProperties = null)
{
    IQueryable<T> query = _dbSet;

    if (filter != null)
    {
        query = query.Where(filter);
    }

    if (InstanceHelper.IsSomething(includeProperties))
    {
        query.Include(includeProperties);
    }

    return query.ToListAsync();
}

我像这样使用它

var teams = await DataAccess.Team.GetManyAsync(e => e.Owner.Id == userId, e => e.Owner);

但它返回具有NULL Owner属性的团队列表。知道我在这里缺少什么吗?

1 个答案:

答案 0 :(得分:2)

您必须使用此

public Task<List<T>> GetManyAsync(Expression<Func<T, bool>> filter = null, params Expression<Func<T, object>>[] includeProperties = null)
{
  foreach (var prop in includeProperties)
  query = query.Include(prop);
  ...
}

你可以拥有多个包含

GetManyAsync(filter ,p => p.prop1 ,p.prop2,...)