Reputation: 8397
So in my ASP.NET MVC application using the Entity Framework, I want to be able to take an existing entity (in this case, PERS936AB_request_original
) duplicate it, change some data, and save the new entity to the database. Here is what I currently have:
var PERS936AB_request_original = db.PERS936AB.Single(r => r.ID == id);
var new_request = DataContractSerialization<PERS936AB>(PERS936AB_request_original);
new_request.Year = currentYear;
db.PERS936AB.AddObject(new_request);
db.SaveChanges();
The DataContractSerialization
method I got from this MSDN Forum thread.
private static T DataContractSerialization<T>(T obj)
{
DataContractSerializer dcSer = new DataContractSerializer(obj.GetType());
MemoryStream memoryStream = new MemoryStream();
dcSer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;
T newObject = (T)dcSer.ReadObject(memoryStream);
return newObject;
}
When I do all of this though, I get the following message. The message makes sense, I just don't know how to "reset" the new entity and give it a new key, and my searches are coming up fruitless.
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
Any help would be fantastic, thanks!
Upvotes: 0
Views: 277
Reputation: 109080
The problem is that the original object is tracked, so you can't add a copy of it. But tracking of the original is not necessary, because you're not updating it. So you have to make sure the object is not tracked. At the same time, you don't need this serialization step. You can simply modify the original object and add it to the context. EF will see it as a brand new instance and ignore its current primary key value:
db.ContextOptions.LazyLoadingEnabled = false;
db.PERS936AB.MergeOption = MergeOption.NoTracking;
var new_request = db.PERS936AB.Single(r => r.ID == id);
new_request.Year = currentYear;
db.PERS936AB.AddObject(new_request);
db.SaveChanges();
I disable lazy loading just for sure: it prevents inadvertent additions of nested objects.
Upvotes: 2
Reputation: 16137
You need to change the ID to 0. EF thinks that they are the exact same entity (even though the year is different) because it checks based on the ID of the object itself. Setting it to 0 will tell EF that it is a brand new entity.
Upvotes: 0