In my context I am deleting one of the existing entities. And in the same context I am trying to add a new entity with using code below:
if (entity != null && EFContext.Entry(entity).State == EntityState.Detached)
{
try
{
var entityName = entity.GetType().Name;
GetObjectContext.AddObject(entityName + "s", entity);
}
catch (Exception ex)
{
log(ex);
throw;
}
}
The problem I have is when I pass the new created entity to the method above, when it is checking the entity state, it throws exception: *
Adding a relationship with an entity which is in the Deleted state is not allowed
I haven't made any relationship with the deleted entity, why would it throw this exception? I am trying to reproduce the issue on another simple project, but can't get to reproduce it there. Does anyone know why would EF would throw that exception?
UPDATE: I have Student and a Backpack entity. Backpack references the Student(one to many). In my case I am deleting one of the backpacks and trying to create a new student entity. And when I am checking the object state I am getting the exception above.
EFContext.Entry(entity) will add the entity to the context at this point.
Most likely the problem here is that the backpack you deleted may have a FK set to 0 after it was deleted or something? If so, then when you add this new Student, that deleted one would end up being under the context of this new Student since it would have an ID of 0 yet. As a temporary fix, try setting the PK of this new Student to -1 before calling Entry(entity) and see if that does anything.