Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop EF From Loading Entities When Assigning Association

Using Entity framework v4, and the POCO entity generator T4 templates.

The problem I have is that the Fixup methods are loading hundreds of entities when I assign an associated entity (see line 4 below).

Dim context = New SomeEntities
Dim list = context.Lists.FirstOrDefault(Function(l) l.ListId = 2)
Dim queryDetail = context.CreateObject(Of QueryDetail)()
queryDetail.CriteriaColumnType = context.CriteriaColumnTypes.FirstOrDefault(Function(cct) cct.CriteriaColumnTypeId = 145)

The CriteriaColumnType entity that is being assigned has a collection of QueryDetail objects, and when the assignment is made, the FixUp method on the CriteriaColumnType entity is lazy loading all of the associated QueryDetails.

How can I create the FK association and attach the CriteriaColumnType entity to my QueryDetail entity without loading all of the CriteriaColumnType's QueryDetail records?

like image 978
Steve Horn Avatar asked Sep 07 '10 18:09

Steve Horn


2 Answers

Do you need lazy loading here? You can turn it off:

context.ContextOptions.LazyLoadingEnabled = false
like image 145
Craig Stuntz Avatar answered Oct 22 '22 20:10

Craig Stuntz


I ran into this problem too. An operation that used to take milliseconds started taking 3-4 seconds to run, all because I added a navigation property pointing to a large table.

I solved the problem by just deleting all the fixup code from the T4 template - our project doesn't need that functionality anyway. I deleted everything from this line:

region.Begin("Association Fixup");

to the next region.End() call. I also deleted all calls to the fixup methods from the property setters, registration of CollectionChanged handlers, and the _settingFK flag.


See this question for more on why the fixup code is there: Why is "Fixup" needed for Persistence Ignorant POCO's in EF 4?. It's trying to make sure that if you change one end of a bidirectional association, the other end is also updated. So, e.g., if you create a new BlogPost and set its User property to a user, the fixup logic will automatically add the post to the user's Posts collection.

marc_s answered the other question by linking to POCO Template Code Generation Options. Removing the fixup code from the T4 template changes the template from #2 (basic POCO with fixup) to #1 (basic POCO without fixup).

like image 1
Richard Beier Avatar answered Oct 22 '22 21:10

Richard Beier