Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Entity Framework perform lambda expressions before or after it fetches the data?

My belief has always been that if BigDataSet is an entity and you assign var someThing = Context.BigDataSet.Single(x => x.Name.Trim().ToUpper.Equals(someName.Trim().ToUpper())); then EF will do some magic to translate your lambda expression into a query, like

SELECT * FROM big_data_set WHERE name = (someName)

But after thinking about it, I can't see a way that it works except by keeping the results of Context.BigDataSet in memory and then performing the search.

Do EF DbSet lambda expressions get turned into SQL, or is it all applied after-the-fact?

Edit: If they do get turned into SQL, how does EF get to "see" the entire stack of things that are going to happen after it fetches the name? If I call instance.MethodA().MethodB(), doesn't that usually mean methods A and B are executed sequentially?

like image 601
tacos_tacos_tacos Avatar asked Jan 17 '14 11:01

tacos_tacos_tacos


2 Answers

Entity Framework does not hit the database until you iterate over your query, essentially its returning IQueryable's which are then converted to a SQL query at the point when you itterate.

var query = context.Employees; // Returns IQueryable<Employee>

var employees = context.Employees.ToList(); // Returns List<Employee> (Hits the database)

If you want a comprehensive explanation you can google "Entity Framework Deferred Execution".

like image 182
BenjaminPaul Avatar answered Nov 16 '22 00:11

BenjaminPaul


EF provider implementations. get Expression trees not lambdas. More about expressions in EF After thinking about your question more, my guess is you didnt realise about Expressions used. The difference between Expression<Function<t,bool>> predicate and just Func<t,bool> predicate. Is important. A provider would NOT be able to use func. It needs an expression tree.

There is a subset of LINQ that can be used in expressions based on the Linq to entities standard.supported queries

try in in debugger and look at the content of a variable of type Expression<Func<t,bool>> . You well see how the lambda has been converted to an expression and it is this expression that the DB provider uses to convert to SQL.

like image 29
phil soady Avatar answered Nov 16 '22 01:11

phil soady