I have tried to clone an object using memberWiseClone()
. It will clone all the value type properties successfully, but will not clone the reference type properties.
The class I'm trying to clone.
public class Document
{
public int OwnerId { get; set; }
public int DocumentManagerId { get; set; }
public virtual User DocumentManager { get; set; }
public Document ShallowCopy()
{
return (Document)this.MemberwiseClone();
}
}
Getting all the correct values for OwnerId
and DocumentManagerId
except DocumentManager
shallowCopy()
is called in my service class update method.(Keeping the state of previous document to log after the document is actually updated)
var document = await this.dbContext.Documents.FirstOrDefaultAsync(x => x.id == documentDto.id);
var prevDocument = document.ShallowCopy();
Im getting the correct result for document.DocumentManager
while not getting it for prevDocument.DocumentManager
. Therefore, this should not be due to any configurations in entity mapping. I wanna know why the virtual object throws an exception when memberWiseCloning.
Workaround used at the moment
I have returned a new instances of both the objects with values manually mapped.
Also i know i can go for deep cloning by serializing the value to memory stream. But i prefer if i can find a better way from memberWiseClone
approach.
Thanks in advance!