I'm trying to copy an entity like described here. In my entity-wrapper base-class I have the following code to copy/clone an entity.
public TBaseEntityModel Clone(TPrimaryKey newPrimaryKey)
{
var newEntity = Activator.CreateInstance<TEntity>();
var clone = DbContext.Entry(newEntity);
clone.State = EntityState.Added;
DbContext.Entry(newEntity).CurrentValues.SetValues(TheEntity);
clone.State = EntityState.Detached;
var cloneEntityModel= (TBaseEntityModel)Activator.CreateInstance(typeof(TBaseEntityModel), DbContext, newEntity);
cloneEntityModel.PrimaryKeyValue = newPrimaryKey;
return cloneEntityModel;
}
After I call the Clone
-method on my concrete entity, it has also it's new Primary Key set to the given value of newPrimaryKey
.
The propblem occurs when I call SaveChanges()
on the underlying context.
It then throws:
Violation of PRIMARY KEY constraint '...'. Cannot insert duplicate key in object 'dbo....'. The duplicate key value is (553a7aa9-0ac2-40a0-820f-43a3b4af745f).
But when I look at my clone
, the PK is set to another value.
So I guess it is something inside the ObjectContext
or even deeper inside.
But I have no idea how to get away the error.