EntityFramework Core - Copying an entity and placing it back into the database
Solution 1
So I went through the "Possible duplicate" thread a bit more than I did when I initially stumbled upon it before creating this one, and there was a not-so-highly upvoted solution that I overlooked that essentially just grabs all of the values at once when retrieving the object from the database - and it doesn't retrieve a reference to that object in the process. My code now looks something like this:
try
{
var incidentToCopy = _context.Incident.Single(i => i.IncidentId == id);
return (Incident) _context.Entry(incidentToCopy).CurrentValues.ToObject();
}
Solution 2
In your IncidentRepository
class try getting the Incident
by using AsNoTracking
and it should get tracked as a new entity when it is added.
public void Clone(int id)
{
// Prevent tracking changes to the object.
var incident = _context.AsNoTracking().SingleOrDefault(i => i.Id == id);
// Setting back to 0 should treat the object Id as unset.
incident.Id = 0;
// Add the Incident while it is untracked will treat it as a new entity.
_context.Incidents.Add(incident);
_context.SaveChanges();
}
Related videos on Youtube
Robert McCoy
Updated on June 05, 2022Comments
-
Robert McCoy almost 2 years
Is there a best practice for doing a copy of an entity, making some changes to it based on user input, and then re-inserting it into the database?
Some other Stackoverflow threads have mentioned that EF will handle inserting new objects for you even if the same primary key exists in the database, but I'm not quite sure that's how EF Core is handling it. Whenever I try and copy an object I get an error of
Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF
Basically I just need a clean way to copy an object, make some changes to it based on user input, and then insert that copy back into the database, and have the Id auto-increment properly. Is there a best practice or simple way of doing this without having to manually set properties to null or empty?
EDIT: Example code for retrieving the object from the database:
public Incident GetIncidentByIdForCloning(int id) { try { return _context.Incident.Single(i => i.IncidentId == id); } catch { return null; } }
Code after retrieving object (As some fields are auto-generated like RowVersion which is a Timestamp):
public IActionResult Clone([FromBody]Incident Incident) { var incidentToCopy = _incidentService.IncidentRepository.GetIncidentByIdForCloning(Incident.IncidentId); incidentToCopy.IncidentTrackingRefId = _incidentService.IncidentRepository.GetNextIdForIncidentCategoryAndType( Incident.IncidentCategoryLookupTableId, Incident.IncidentTypeLookupTableId).GetValueOrDefault(0); incidentToCopy.RowVersion = null; incidentToCopy.IncidentId = 0; //This will fail with or without this line, this was more of a test to see if manually setting would default the insert operation, such as creating a brand new object would normally do. incidentToCopy.IncidentCategoryLookupTableId = Incident.IncidentCategoryLookupTableId; incidentToCopy.IncidentTypeLookupTableId = Incident.IncidentTypeLookupTableId; var newIncident = _incidentService.IncidentRepository.CreateIncident(incidentToCopy); ...
I realize I could just make an entirely new object and do left-hand copying, but that seems terribly inefficient and I want to know if EF Core offers better solutions.
-
Robert McCoy about 7 yearsI believe this caused issues when trying to insert it back into the database, as it knew it was not being tracked and did not like that very much. I went ahead and grabbed all of the CurrentValues of the object in my retrieval method and now it appears to be working (see my response to this thread for more info)
-
dkmann about 7 years@RobertMcCoy DbContext does not know about non-tracked entities. Calling Add enables tracking on the entity so it is queued to be added to the database. What exception did you receive upon running the code?
-
Captain Prinny over 3 yearsThis wont work with auto-incrementing key, as it'll interpret the 0 as an explicit id set