Using LINQ to Entity efficiently with First/FirstOrDefault/Last/LastOrDefault/Single/SingleOrDefault
We generally use these extension methods First/FirstOrDefault/Last/LastOrDefault/Single/SingleOrDefault with predicates like
Selecting multiple items with same approach
It adds up extra extension methods but certainly saves from retrieving all column records from DB.
Implementation of projection before calling FirstOrDefault or similar method on architecture level.
Sometime back I had created Repository Pattern (http://vikutech.blogspot.in/2015/01/architecture-solution-composting-repository-pattern-unit-of-work-dependency-injection-factory-pattern.html), let's see how can we integrate in same.
NOTE: TModel is defined on class level. Check the implementation from above provided link.
This can be also done as extension method if there is no Repository pattern, in that TModel need to be defined on function level public virtual TResult FirstOrDefault<TModel, TResult>(Expression<Func<TModel, bool>> filter, Expression<Func<TModel, TResult>> values).
The above function takes first parameter as expression to filter result and second value as expression for projection.
Usage example:
ctx=> ctx.Model.FirstOrDefault(item => item.Id == 1 )
Or ctx=> ctx.Model.Where(item => item.Id == 1 ).FirstOrDefault()
What is the problem with these?
FirstOrDefault or similar methods immediately loads all data at once. So, let's say we have fifty columns on table then all those columns data would be retrieved from DB and saved into memory.
This link gives a fair idea of different function behavior. https://msdn.microsoft.com/en-us/library/bb882641.aspx.
So, even if we require only one value from selected field it retrieves all values.
What is the solution?
The solution is pretty simple. Whenever we need selected items better to do projection before calling FirstOrDefault or similar methods.
Ex:
Selecting single item
Selecting single item
ctx.Model.Where(itm => itm.Id == 1)
.Select(itm => itm.Name).FirstOrDefault();
Selecting multiple items with same approach
ctx.Model.Where(itm => itm.Id == 1)
.Select(itm => new { itm.Id, itm.Name }).FirstOrDefault();
It adds up extra extension methods but certainly saves from retrieving all column records from DB.
Implementation of projection before calling FirstOrDefault or similar method on architecture level.
Sometime back I had created Repository Pattern (http://vikutech.blogspot.in/2015/01/architecture-solution-composting-repository-pattern-unit-of-work-dependency-injection-factory-pattern.html), let's see how can we integrate in same.
/// <summary>
/// Returns the first element of a sequence, or a default value if sequence contains no elements
/// after applying required filters with projection.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="filter">The filter for query.</param>
/// <param name="values">The expected values.</param>
/// <returns>Object as per projected expression.</returns>
public virtual TResult FirstOrDefault<TResult>(Expression<Func<TModel, bool>> filter,
Expression<Func<TModel, TResult>> values)
{
var query = DbContext.Set<TModel>();
if (filter != null)
{
query = query.Where(filter);
}
return query.Select(values).FirstOrDefault();
}
NOTE: TModel is defined on class level. Check the implementation from above provided link.
This can be also done as extension method if there is no Repository pattern, in that TModel need to be defined on function level public virtual TResult FirstOrDefault<TModel, TResult>(Expression<Func<TModel, bool>> filter, Expression<Func<TModel, TResult>> values).
The above function takes first parameter as expression to filter result and second value as expression for projection.
Usage example:
UnitOfWork.UserRepository.FirstOrDefault(usr => usr.Id == 1, //userId
usr => usr.Name)
Or UnitOfWork.UserRepository.FirstOrDefault(usr => usr.Id == 1, //userId
usr => new { usr.Id, usr.Name });
Comments
Post a Comment