10

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!

  • Have you tried to `Include` the parent object in the query? See: http://stackoverflow.com/questions/19319116/include-vs-load-performance-in-entityframework – Stefan Jun 01 '15 at 09:52
  • I've tried including the parent but the reference won't be loaded. Maybe I'm doing something wrong... `context.tblDiscountLevel.Include("Condition").Where(lv => lv.LevelDiscountID == this.LevelDiscountID ).ToList()` – Raphael Huber Jun 01 '15 at 10:33
  • Are you using `code first` or a edmx? When using code first the navigation property to the parent should be `virtual` and contain some naming conventions to make it work out of the box. If you are using a edmx my experience is not enough to help you here. – Stefan Jun 01 '15 at 10:50
  • I'm using an edmx-file :/ I looked it up and the parent navigation property wasn't virtual. Changing that also didn't make any difference – Raphael Huber Jun 01 '15 at 11:16

1 Answers1

1

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.