Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4 Loading Reference Exception

I'm having troubles loading the reference to a parent object in Entity Framework 4. Due to Lazy Loading the reference to the parent object (Condition) is not loaded on the child object (DiscountLevel), so I try to load it with:

if(!this.ConditionReference.IsLoaded) this.ConditionReference.Load();

But this throws the following exception:

the entity reference could not be loaded because it is not attached to an objectcontext

So if I try to attach the existing child object (DiscountLevel) to the Object Context (and then load the parent reference afterwards):

context.AttachTo("tblDiscountLevel", this);

I get the following exception:

An object with the same key already exists in the ObjectStateManager. The existing object is in the Detached state. An object can only be added to the ObjectStateManager again if it is in the added state.

I feel like I'm doing something wrong in the first place, but I can't figure out what. So every help on this topic is very appreciated. Let me know if you need additional information!

like image 341
Raphael Huber Avatar asked Jun 01 '15 09:06

Raphael Huber


1 Answers

I stumbled upon the problem and it didn't have to do anything with the code above: There are a few calculations in various overwritten OnChange-methods in DiscountLevel that fail if they're called too early - in this case on the initial loading from the DB. This resulted the Child object to be not properly initialized - appearing like it was not loaded at all from the outside.

Implementing a simple bool-variable that supressed the execution of the OnChange-methods on the initial load made everything work as expected. There might be a more elegant solution with the features the Entity Framework provides, but this worked for me.

like image 121
Raphael Huber Avatar answered Sep 30 '22 20:09

Raphael Huber