Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code First - Include(x => x.Properties.Entity) a 1 : Many association

Given a EF-Code First CTP5 entity layout like:

public class Person { ... } 

which has a collection of:

public class Address { ... }

which has a single association of:

public class Mailbox { ... }

I want to do:

PersonQuery.Include(x => x.Addresses).Include("Addresses.Mailbox")

WITHOUT using a magic string. I want to do it using a lambda expression.

I am aware what I typed above will compile and will bring back all Persons matching the search criteria with their addresses and each addresses' mailbox eager loaded, but it's in a string which irritates me.

How do I do it without a string?

Thanks Stack!

like image 305
VulgarBinary Avatar asked Mar 01 '11 19:03

VulgarBinary


People also ask

How do you create a many-to-many relationship in EF core?

Many-to-many relationships require a collection navigation property on both sides. They will be discovered by convention like other types of relationships. The way this relationship is implemented in the database is by a join table that contains foreign keys to both Post and Tag .

How do I code first in Entity Framework?

Step 1 − First, create the console application from File → New → Project… Step 2 − Select Windows from the left pane and Console Application from the template pane. Step 3 − Enter EFCodeFirstDemo as the name and select OK. Step 4 − Right-click on your project in the solution explorer and select Manage NuGet Packages…

How do you load entities or data in EF?

Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading. The techniques shown in this topic apply equally to models created with Code First and the EF Designer.


2 Answers

For that you can use the Select method:

PersonQuery.Include(x => x.Addresses.Select(a => a.Mailbox)); 

You can find other examples in here and here.

like image 73
Morteza Manavi Avatar answered Nov 02 '22 22:11

Morteza Manavi


For any one thats still looking for a solution to this, the Lambda includes is part of EF 4+ and it is in the System.Data.Entity namespace; examples here

http://romiller.com/2010/07/14/ef-ctp4-tips-tricks-include-with-lambda/

like image 24
Ricky Gummadi Avatar answered Nov 03 '22 00:11

Ricky Gummadi