Linq repository and GetTable()

2019-04-15 00:26发布

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条回答
成全新的幸福
2楼-- · 2019-04-15 01:13

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.

查看更多
登录 后发表回答