The usual way to copy the properties of one entity to another would be to implement the ICloneable interface and do a proper, deep copy of all properties from one instance to the other.

However, when there are no complex properties or related objects, this trick using Entity Framework will successfully copy basic properties from one entity to another:

var propInfo = entity1.GetType().GetProperties();
foreach (var item in propInfo) {
    entity2.GetType().GetProperty(item.Name).SetValue(entity2, item.GetValue(entity1, null), null);
}

Note that this copies all properties, including ones you may not want copied, including the Id of the object itself, as well as any concurrency fields (RowVersion), etc. If you want entity2 to preserve certain values, assign those values to variables before doing the copy and overwrite them after.

Example:

int iOriginalId = entity2.Id;
var propInfo = entity1.GetType().GetProperties();
foreach (var item in propInfo) {
    entity2.GetType().GetProperty(item.Name).SetValue(entity2, item.GetValue(entity1, null), null);
}
entity2.Id = iOriginalId;

Source: https://stackoverflow.com/a/21669911/4669143

Published On: March 8, 2019Categories: Entity Framework