Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Include in Entity Framework 4 with lambda expressions

I've seen many articles about how to overcome this matter, all related to CTP4, Or adding my own extension methods.

Is there an "official" EF4 included way to use lambda expressions inside include (for both first level relations and also 2nd and more level) or is it eventually was not included in the RTM ?

It there is one - I would be glad to learn how to do it, as using lambda expression in my code now (with #system.data.entity #system.data.linq) still gives me:

Cannot convert lambda expression to type 'string' because it is not a delegate type on:

var customers = from c in context.Customers.Include(c=>c.Phone) 
like image 400
Dani Avatar asked Dec 28 '10 08:12

Dani


People also ask

Can you use lambda expression instead of LINQ query?

So performance-wise, there's no difference whatsoever between the two. Which one you should use is mostly personal preference, many people prefer lambda expressions because they're shorter and more concise, but personally I prefer the query syntax having worked extensively with SQL.

What is lambda expression in Entity Framework?

The term 'Lambda expression' has derived its name from 'lambda' calculus which in turn is a mathematical notation applied for defining functions. Lambda expressions as a LINQ equation's executable part translate logic in a way at run time so it can pass on to the data source conveniently.

How do you pass lambda expression?

If we need to pass a lambda expression as an argument, the type of parameter receiving the lambda expression argument must be of a functional interface type. In the below example, the lambda expression can be passed in a method which argument's type is "TestInterface".


2 Answers

The RTM version of Entity Framework 4.1 actually includes extension methods in the EntityFramework.dll file, for eager loading with lambda through the Include function. Just include the DLL in your project and you should be able to write code like:

var princesses1 = context.Princesses.Include(p => p.Unicorns).ToList(); 

Remember to add an Import/Using statement to include the System.Data.Entity namespace. Otherwise the compiler cannot find the extension methods. E.g:

using System.Data.Entity; 

See this ADO.NET team blog article for more information.

like image 142
cecilphillip Avatar answered Sep 30 '22 20:09

cecilphillip


Although this is implied in the question, for anyone else who has the same problem where they can't use lambdas with .Include, make sure you have this:

using System.Data.Entity; 
like image 22
AaronLS Avatar answered Sep 30 '22 19:09

AaronLS