0

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.

Exception for documentManager property

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!

anilcemsimsek
  • 803
  • 10
  • 21
Lasanga Guruge
  • 832
  • 1
  • 5
  • 15
  • Hi, there is a great post about deep cloning with you can find pros and cons of each approach. Did you check it? You can consider "copy constructor" approach. https://stackoverflow.com/questions/78536/deep-cloning-objects – anilcemsimsek May 27 '20 at 05:12
  • Hi @anilcemsimsek , yeah I've read that. Serializing will work, i wanna know why the virtual object throws an exception when `memberWiseCloning`. If I use the copy constructor approach, my inner object will change if its values are updated afterwards due to reference type. – Lasanga Guruge May 27 '20 at 05:36
  • @Thanks for clarifying the question. – anilcemsimsek May 27 '20 at 05:58

0 Answers0