简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM