Clone entity values with Entity Framework

Clone entity values with Entity Framework

Often you want to duplicate entities or their values in order to save an entity with a new ID. But what is the best way to do this?

There are many examples in the vastness of the Internet based on Object.Clone() or Reflection.
But this is not necessary. Entity Framework has inherent methods to copy values.

DbContext Clone

To simply copy values from an existing entity to a new entity, you have two stable ways.

Copy values to a local var first:

var values = db.Entry(oldEntity).CurrentValues.Clone();
var newEntity = ...
db.Entry(newEntity ).CurrentValues.SetValues(values);
newEntity.Id = 0;

Directly copy values from old entity to new entity.

db.Entry(newEntity).CurrentValues.SetValues(oldEntity);
newEntity.Id = 0;

These methods are stable and not based on any Reflection tinkering.