We have an audit table in our database, and on update the old and new values are serialized to XML and stored in the same row. The objects are currently deep-cloned thus:
public EntityObject CloneEntity(EntityObject obj)
{
DataContractSerializer dcSer = new DataContractSerializer(obj.GetType());
MemoryStream memoryStream = new MemoryStream();
dcSer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;
EntityObject newObject = (EntityObject)dcSer.ReadObject(memoryStream);
return newObject;
}
Whilst this works, it generates vast amounts of data due to the related records pulled from the deep clone, with hundreds of thousands of reads from the DB on dcSer.WriteObject(memoryStream, obj)
, and an eventual MemoryStream size of some 200MB, not to mention the amount of data being written back to the DB. Not ideal.
So I would like to do a memberwise clone instead, as it is my understanding that a memberwise clone would leave the object references out, and avoid copying all the related Entity Framework models.
So I did this:
public EntityObject CloneEntity(EntityObject obj)
{
EntityObjectAuditable auditable = (EntityObjectAuditable)obj; // invalid cast exception
return auditable.ShallowCopy();
}
// ....
public class EntityObjectAuditable : EntityObject
{
public EntityObjectAuditable ShallowCopy()
{
return (EntityObjectAuditable)this.MemberwiseClone();
}
}
but I get an invalid cast exception because the actual type of the incoming EntityObject
is a subclass relating to the table itself.
I have also tried using an extension method to access MemberwiseClone()
, but extension methods cannot access protected methods.
So, how can I create a shallow copy of a generic EntityObject?