Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include all underlying navigation properties automatically with entity framework

Scenario: I'd like to add an entity to the database that would have navigation properties and that entity has navigation properties.. and so on. Basically the tables in the database are connected with each other - all of them.

I use EF4.3 and context/request pattern, so I don't want to enable Lazy loading; it would simply just take too much time to load the entity that I need. So far I have learned there is no other way to do it than to use the include method like this:

 context.Set<TEntity>().include("navproperty1").include("navproperty1.navproperty1.1")... and so on.

This way the maintainability would be bad, plus it's a lot of code but is there any other way if I don't want to manually write all the includes for every entity type?

like image 623
JahManCan Avatar asked Mar 24 '23 01:03

JahManCan


1 Answers

There are a lot of questions here. I'll try to address each point.

First, Lazy loading isn't always faster. Specially if you are loading ALL the relations.

Second, always avoid "magic strings". I don't know if the Include method which receives a lambda expression (it's an IQueryable extension) is available for EF 4.3. If it's not, you should implement it yourself like shown here and use:

context.Set<TEntity>().include(t => t.NavProp)

"A" entity" has 1 : n relation to "B" entity but "B" entity has n : m relation to "C" entity. And if I wouldnt inlcude "C" to "A" and then try to call context.SaveChanges() then all the data would lost between "B" and "C"

I don't really know what you meant. But, if you want to select a sub-navigation property which belongs to an item in a list you should use this in EF 5: (not sure if it works in 4.3)

context.Set<TEntity>().Include(t => t.Collection.Select(c => c.SubProp))

Other expressions can be found here

If you clarify on that quote maybe I can help more.

like image 137
Saulo Vallory Avatar answered Apr 05 '23 23:04

Saulo Vallory