Skip to main content

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
 ctx=> ctx.Model.FirstOrDefault(item => item.Id == 1 )  
 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.

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.
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 (, 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)  
 UnitOfWork.UserRepository.FirstOrDefault(usr => usr.Id == 1, //userId  
         usr => new { usr.Id, usr.Name });  

Popular posts from this blog

Architecture solution composting Repository Pattern, Unit Of Work, Dependency Injection, Factory Pattern and others

Project architecture is like garden, we plant the things in certain order and eventually they grow in similar manner. If things are planted well then they will all look(work) great and easier to manage. If they grow as cumbersome it would difficult to maintain and with time more problems would be happening in maintenance.

There is no any fixed or known approach to decide project architecture and specially with Agile Methodology. In Agile Methodology, we cannot predict how our end products will look like similarly we cannot say a certain architecture will fit well for entire development lifespan for project. So, the best thing is to modify the architecture as per our application growth. I understand that it sounds good but will be far more problematic with actual development. If it is left as it is then more problems will arise with time. Just think about moving plant vs a full grown tree.

Coming to technical side, In this article, I will be explaining about the various techniques tha…

LDAP with ASP.Net Identity Core in MVC with project.json

Lightweight Directory Access Protocol (LDAP), the name itself explain it. An application protocol used over an IP network to access the distributed directory information service.

The first and foremost thing is to add references for consuming LDAP. This has to be done by adding reference from Global Assembly Cache (GAC) into project.json

"frameworks": { "net461": { "frameworkAssemblies": { "System.DirectoryServices": "", "System.DirectoryServices.AccountManagement": "" } } },
These System.DirectoryServices and System.DirectoryServices.AccountManagement references are used to consume LDAP functionality.

It is always better to have an abstraction for irrelevant items in consuming part. For an example, the application does not need to know about PrincipalContext or any other dependent items from those two references to make it extensible. So, we can begin with some bas…

Configuring Ninject, Asp.Net Identity UserManager, DataProtectorTokenProvider with Owin

It can be bit tricky to configure both Ninject and Asp.Net Identity UserManager if some value is expected from DI to configure UserManager. We will look into configuring both and also use OwinContext to get UserManager.

As usual, all configuration need to be done on Startup.cs. It is just a convention but can be used with different name, the important thing is to decorate class with following attribute to make it Owin start-up:

[assembly: OwinStartup(typeof(MyProject.Web.Startup))]
Ninject configuration

Configuring Ninject kernel through method which would be used to register under Owin.

public IKernel CreateKernel() { var kernel = new StandardKernel(); try { //kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); // TODO: Put any other injection which are required. return kernel; } catch { kernel.Dispose(); throw; }…