Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-Level Includes in CodeFirst - EntityFrameWork

Tags:

It is working code;

IQueryable<Product> productQuery = ctx.Set<Product>().Where(p => p.Id == id).(Include"Contexts.AdditionalProperties.Field"); 

But you know that it could not produce compile time error if we made mistake in string statement in "Contexts.AdditionalProperties.Field"

I would like to write code below;

IQueryable<Product> productQuery = ctx.Set<Product>().Where(p => p.Id == id).Include(p => p.Contexts); 

But above statement could not give chance to define AdditionalProperties and Field.

What should we do?

I would like to write as more than one include for build query.

Thanks.

like image 519
Nuri YILMAZ Avatar asked Jan 20 '11 18:01

Nuri YILMAZ


People also ask

What is include and ThenInclude in Entity Framework?

Entity Framework Classic ThenIncludeThe ThenInclude method moves the chaining level to the property included. It allows us to include related objects from the next level. ThenInclude is a syntactic sugar method to make it easier and clearer to include multiple related objects.

What is include method in Entity Framework?

Entity Framework Classic Include The Include method lets you add related entities to the query result. In EF Classic, the Include method no longer returns an IQueryable but instead an IncludeDbQuery that allows you to chain multiple related objects to the query result by using the AlsoInclude and ThenInclude methods.

What is lazy loading in Entity Framework?

Lazy loading is the process whereby an entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed. Lazy loading means delaying the loading of related data, until you specifically request for it.

What is split entity?

Entity splitting gives you the ability to take a single entity in your model and split it into multiple physical database tables. It is essentially the opposite of table splitting.


1 Answers

If AdditionalProperties is a single reference to another object:

using System.Data.Entity; ... IQueryable<Product> productQuery = ctx.Set<Product>()         .Include(p => p.Contexts.AdditionalProperties.Field)         .Where(p => p.Id == id); 


If AdditionalProperties is a collection then you can use the Select method:

IQueryable<Product> productQuery = ctx.Set<Product>()         .Include(p => p.Contexts.AdditionalProperties.Select(a => a.Field))         .Where(p => p.Id == id); 

Don't forget to import System.Data.Entity namespace in your class file!

like image 136
Morteza Manavi Avatar answered Oct 04 '22 03:10

Morteza Manavi