Entity Framework - Projection Queries


Projection is the process of transforming the result of a query. Projection is when the result of a query is output to a different type than the one queried. Projection can be to an anonymous type, but could also be to a concrete type. 

Projection queries improve the efficiency of the application, by retrieving specific fields from the database. Some projection styls are as follows:-

Single Object

First() or FirstOrDefault enumerable methods is used to retrive single object, this method returns the first element of a sequence.
The difference between First and FirstOrDefault is that First() will throw an exception, if there is no result data for the supplied criteria whereas FirstOrDefault() returns default value null, if there is no result data. Single() or SingleOrDefault can be used to get the single object. But there is difference between First() or FirstOrDefault and Single() or SingleOrDefault, First() or FirstOrDefault will return the top 1 record from the result set and Single() or SingleOrDefault will throw exception if result set has more than one values.

using (var ctx = new EFSourceDBEntities())
{
  var employee = (from s in ctx.Employees where s.Name == "xyz"
                  select s).FirstOrDefault<Employees>();
}
using (var ctx = new EFSourceDBEntities())
{ 
  var employee = (from s in ctx.Employees where s.Name == "xyz"
                   select s).SingleOrDefault<Employees>();
}

Objects List
ToList() enumerable method can be used to get the list of employees whose name is xyz.

using (var ctx = new EFSourceDBEntities())
{
 var empList = (from s in ctx.Employees where s.Name == "xyz" select s).ToList();
}

 

Order 
To get data/list in particular order, you can use orderby keyword. 

using (var ctx = new EFSourceDBEntities())
{
   var empList = (from s in ctx.Employees where s.Name == "xyz" orderby s.Name ascending select s).ToList();
}

 

Group By
To get data/list in particular group, you can use group by keyword.

using (var ctx = new EFSourceDBEntities())
{
   var empList = from s in ctx.Employees group s by s.Designation into EmployeeByDesignation select EmployeeByDesignation;
}

 

Praesent mattis

Pellentesque viverra vulputate enim. Aliquam erat volutpat. Pellentesque tristique ante ut risus. Quisque dictum. Integer nisl risus, sagittis convallis, rutrum id, elementum congue, nibh. Suspendisse dictum porta lectus. Donec placerat odio vel elit.

Read More