Archive

Posts Tagged ‘Association’

EF Navigation Property Looping Issue

This is a problem i faced today, while working on a project which uses EF 4.0.

In my db, there are two tables, say Item and Status. Item’s status is referring status table. Note that there are another tables like ‘Category’, ‘Type’ which are also referred by ‘Item’ table. This table structure wasn’t changed recently and was working fine with EF (4.0 with ObjectContext).  Recently we loaded around 1 million items to Item table for testing. After that, item updating and inserting started to work abnormal way. when i closely look in to matter, it was happening when i assign a value to reference property. As a example,

exitingItem.ItemStatusId = itemStatus;
context.SaveChanges();

when i execute first line, it is going loop forever. What i wonder is, this is happening only when i assign value. so this is happening on context. even not before save to DB.

After goggling, i found the exactly same problem on stackoverflow.

http://stackoverflow.com/questions/6361272/ef-navigation-property-looping-issue

This explains what is happening with POCO generated class.

I have a another project, there i used EF5 with DbCotext. when i test the same scenario with same DB, it was working fine. Reason is DbContext does not generate Fixup methods.

Solution : As above link explained, solutions are

  • Remove the Person collection from your AddressStatusLookup class (as you already tried with success). It’s usefulness is questionable anyway.
  • Or: Don’t work with lazy loading
  • Or: Remove the fixup methods from the generated classes. (Perhaps it’s possible to tweak the T4 templates and create a custom template to suppress generating these methods in the first place, but I am not sure.)

With the time frame, disabling the Lazy loading is not possible with us.

removing the navigation property i didn’t consider.

I went with the Removing fixup methods. This was also not straight forward. One article explained to delete fixup generating sections on POCO as this.

If you open the .tt fle, you’ll notice region.Begin("Association Fixup"); (line 303) which ends on line 632. You might want to delete that area and see what you’ll get.

But i had to delete calls to the fixup methods from the property setters, registration of CollectionChanged handlers, and the _settingFK flag from POCO to successfully generate the classes. This way update and insert is happening as normally with 1 million data.

(purpose of fixup is to ensure that each end of a bidirectional relationship stays in sync with the other, but since we use entities via EF context, not interdependently we don’t have to worry for these fixups)