How to include all underlying navigation properties automatically with entity framework

c# entity-framework lazy-loading navigation-properties

Question

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?

1
4
5/8/2013 12:49:09 PM

Popular Answer

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.

7
6/25/2013 9:59:16 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow