Problem

Entity Added Twice!

Today I come across a problem in Stack Overflow which a developer asked why an entity was added twice in SQL even if he only added it once in the second context.

You can read the full problem here

Example

So what's wrong with this code?


Solution

In fact, the order has not been added twice, the first order created has been saved and the second order has been saved.

But why the first order has been saved?

The customer contains a list of order and AutoDetectChangesEnabled configuration was true.

By adding the first order in the first context, a change has been detected and the customer list which was previously null are now containing the first order. Then by adding the second order in the second context, another change has been detected and the second order is added to the customer list which already contains the first order.

So even if you only add the second order in the second context, Entity Framework save the related customer and all it's related orders (The first and second order).

Example

Here is an equivalent code which explain more in detail what is happening.


Conclusion

This kind of issue remember us to be careful how we use Entity Framework since a lot of logic is done under the hood like automatically in one to many relation creating a list and adding the entity.


Share your experience

  • Did you have a similar issue? How did you fix it?
  • Did this solution helped you?