Using Include in Entity Framework 4 with lambda expressions

C#Entity Framework-4Lambda

C# Problem Overview


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)

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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;

Solution 3 - C#

No there is no official support for Include with lambda expression in RTM at the moment. I'm using this.

When we are talking about CTP4 we are meaning Entity Framework Feature. It is newer API than EF4. It mainly includes Code First and few other improvements.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniView Question on Stackoverflow
Solution 1 - C#cecilphillipView Answer on Stackoverflow
Solution 2 - C#AaronLSView Answer on Stackoverflow
Solution 3 - C#Ladislav MrnkaView Answer on Stackoverflow