What is the best way to write queries in the Entity Framework

What is the best way to record query performance. for example, I can write a request to get all employees by a certain last name, following

ObjectQuery<Employee> queryEmp = context.CreateQuery<Employee>( "Select value e from Employees AS e Where e.LastName = @lastName", new ObjectParameter("lastName", typeof(String)) { Value = "Farooqi" }); ObjectResult<Employee> results = query.Execute(MergeOption.AppendOnly); 

OR

 var v = from e in context.Employees where e.LastName == "Farooqi" select e; 

OR

 context.Employees.Where(e => e.LastName == "Farooqi"); 

OR

 context.Employees.Where("LastName = @lastName", new ObjectParameter("lastName", typeof(String)) { Value = "Farooqi" }); 

My question is which method for queries is best. What I'm confused with is that I think (but not sure) that using the last three methods other than the first will retrieve all the employee records from the database, and then listing all the records that will be reconfigured, which fulfill the given condition, so I think that the last three paths will require more time than the first, so I used only the first. But what is the best in reality I do not know. Do all methods only retrieve a database of records that satisfy the condition or retrieve all records from db, and then are listed to return the filtered records to the end of the application?

+7
source share
1 answer

There is a slight difference; 2nd / 3rd has the advantage of ensuring the correctness of the type during compilation, since the expression tree will not compile if LastName does not exist or, say, int , avoids typos and the magic string problem.

Repeat your assumption of the return of everything; not. The second / third is compiled into expression trees , which can be deconstructed and used to create the correct SQL (filtering the server). Very smart, but often misunderstood. The key point is that it is Queryable.Where (taking Expression<Func<T, bool>> ) and not Enumerable.Where (taking a Func<T, bool> ). Feel free to trace.

Similarly, between the 1st and 4th slight difference - both will be filtered on the server.

+9
source

All Articles