How to include all underlying navigation properties automatically with entity framework

邮差的信 提交于 2021-02-07 08:26:09

问题


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:


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.




回答2:


take look at this snippet

var dbQuery =
context.Letters.Where(letter => letter.ID == myId)
   .Include(l => l.Recipients.Select(y => y.PersonTitle))//this will include letter.Recipients.PersonTitle
   .Include(l => l.PersonTitle)
   .Include(l => l.Rank)
   .Include(l => l.JobTitle);
theLetter = dbQuery.FirstOrDefault();// maybe null returned

this line

context.Letters.Include(l => l.Recipients.Select(y => y.PersonTitle))

will get letter(s) with its Recipients and you can access PersonTitle which is exist inside Recipients navigation property

thats means navigation property withen navigation property



来源:https://stackoverflow.com/questions/16439872/how-to-include-all-underlying-navigation-properties-automatically-with-entity-fr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!