簡體   English   中英

Where子句不包含在SQL查詢中

[英]Where clause not included in SQL query

我目前正在使用EntityFramework 6.0在C#4.0中創建一個應用程序。

我正在嘗試從數據庫中檢索項目列表,但問題是EF框架生成的SQL查詢不包含where子句。

因此,整個表/視圖加載到內存中,只需10秒即可獲得2或3個項目。

下面是我的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子句?

我希望我對這些信息足夠清楚,我很抱歉我的英語。 這不是我的母語:/

無論如何,謝謝你的幫助

從中更改方法簽名

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

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

你仍然可以像現在一樣用lambda調用它。 Where在數據庫中讀取的完整列表中用作“linq-to-objects”。 使用Expression EF可以讀取生成所需的sql。

where參數的類型是Func<TEntity, bool> ,so

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM