Linq repository and GetTable<T>()

[亡魂溺海] 提交于 2019-12-06 13:57:45

问题


I'm following the fairly standard L2S repository pattern, using the following as one of the methods

public IEnumerable<T> GetAllByFilter(Func<T, bool> expression)
 {
     return _dataContext.GetTable<T>().Where(expression);
 }

I'm a bit miffed to see that the call to GetTable appears to literally get the table, with the Where expression presumably evaluated in-memory afterwards.

So a simple call like

var order = GetAllByFilter(o => o.OrderNumber == 1);

which should only ever return one record, is fetching the entire 50000 record database.

Is Linq normally this bad? Or am I missing something?


回答1:


Change:

public IEnumerable<T> GetAllByFilter(Func<T, bool> expression)
{
    return _dataContext.GetTable<T>().Where(expression);
}

To:

public IQueryable<T> GetAllByFilter(Expression<Func<T, bool>> expression)
{
    return _dataContext.GetTable<T>().Where(expression);
}

This will use Queryable (i.e. SQL) instead of Enumerable (i.e. local) and therefore will perform much better.



来源:https://stackoverflow.com/questions/3873753/linq-repository-and-gettablet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!