Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 实体框架Include()返回空导航属性_C#_Asp.net Mvc_Entity Framework_Entity Framework 6 - Fatal编程技术网

C# 实体框架Include()返回空导航属性

C# 实体框架Include()返回空导航属性,c#,asp.net-mvc,entity-framework,entity-framework-6,C#,Asp.net Mvc,Entity Framework,Entity Framework 6,我对Include函数有问题。我有一个团队类,它的所有者属性类型为Owner。我有一个helper函数包装我的EF调用,如下所示 public Task<List<T>> GetManyAsync( Expression<Func<T, bool>> filter = null, Expression<Func<T, object>> includeProperties = null) { IQuer

我对Include函数有问题。我有一个团队类,它的所有者属性类型为Owner。我有一个helper函数包装我的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();
}

但它会返回具有空所有者属性的团队列表。你知道我在这里遗漏了什么吗?

你必须用这个

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);
  ...
}

在所有者财产声明之前是否指定了
virtual
关键字?首先,您必须检查数据库中的
null
。还有,为什么不传递这个表达式呢?你为什么要先调用
GetPropertyName()
,它会返回什么?@navonel,
virtual
关键字是允许延迟加载。一旦你渴望加载属性,
virtual
就不再需要了(尽管你也会失去更改跟踪)。@haim770你是对的。只是想确定op有没有if@haim770GetPropertyName获取在includeProperty参数中指定的属性名称。我只是在测试。我过去常常将字符串传递到include中,但由于“column/property”名称的所有硬编码,它变得很混乱。我从上面粘贴的代码中删除了它。是的,我可以在数据库中看到一个值。Owner_Id中有一些整数。虽然这段代码可以回答这个问题,但最好包含一些上下文,解释它是如何工作的以及何时使用它。从长远来看,纯代码答案是没有用的。显然,当我使用include时,它不会将其应用于实例本身,它会返回一个IQueryable,我必须使用它,然后像您那样重新分配它。但是foreach循环不起作用。但是谢谢@M.Azad如何迭代表达式类型的对象?我现在很好奇…@鸭嘴兽我更新了我的答案
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,...)