SQL查询中未包含Where子句。

7

我正在使用C# 4.0和EntityFramework 6.0创建一个应用程序。

我尝试从数据库中检索项目列表,但问题是EF框架生成的SQL查询不包括where子句。

因此,整个表格/视图都加载到内存中,仅获取2或3个项目需要大约10秒钟。

下面是我的GenericRepostitory的方法:

public IList<TEntity> GetList(Func<TEntity, bool> where, params Expression<Func<TEntity, object>>[] navigationProperties)
{
    using (var dbContextScope = contextScopeFactory.CreateReadOnly())
    {
        IQueryable<TEntity> dbQuery = Context.Set<TEntity>().AsQueryable();

        foreach (Expression<Func<TEntity, object>> navigationProperty in navigationProperties)
            dbQuery = dbQuery.Include<TEntity, object>(navigationProperty);

        var list = dbQuery
            .AsNoTracking()
            .Where(where);

        Context.Database.Log = s => Debug.WriteLine(s);

        return list.ToList<TEntity>();
    }
}

我这样调用它:
var repository = repositoryFactory.Get<Context, Entity>();
var items = repository.GetList(x => x.FakeID <= 10); 

返回结果很好,但检索需要大约10秒钟。 当调试程序写出生成的SQL查询时,where子句不在其中。
如何修改我的GetList函数以包括where子句?
希望这些信息已经足够清晰,对于我的英语我感到抱歉。 这不是我的母语:/
无论如何,感谢您的帮助。

1
如果不是 DbContext,那么 Context 是什么?这里不应该需要使用 AsQueryableContext.Set<TEntity>() - ta.speot.is
是的,它不应该出现,我已经将其删除了。因为我被这个问题困扰了几个小时,尝试了很多不同的方法... - Mica
2个回答

7

将您的方法签名更改为

GetList(Func<TEntity, bool> where, ...

为了

GetList(Expression<Func<TEntity, bool>> where, ...

你仍然可以使用lambda表达式来调用它,就像你现在所做的那样。 Where被用作"linq-to-objects",在从数据库读取的完整列表上使用。通过Expression,EF可以读取并生成所需的sql语句。

7

where参数的类型是Func<TEntity, bool>,因此

dbQuery.Where(where)

使用Enumerable.Where扩展方法,在过滤之前将数据加载到内存中。如果你想使用Queryable.Where方法(将被转换为SQL),则需要一个Expression<Func<TEntity, bool>>参数。

public IList<TEntity> GetList(Expression<Func<TEntity, bool>> where, 
                              params Expression<Func<TEntity, object>>[] navigationProperties)

感谢您的解释,我现在更清楚它们之间的区别了! :) - Mica

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接