How to (shallow) copy an entity

Posts   
 
    
JanRHansen
User
Posts: 37
Joined: 02-Jan-2019
# Posted on: 12-Sep-2020 15:16:45   

Hello

For the sake of simplicity, lets say I have an Invoice -> InvoiceDetail table structure, and wanted to create a credit note based on an invoice. In that case, I would like similar but not identical entities created, so for example Invoice A - item x (quantity 1, price 100)

was to generate

Invoice B (the credit note) - item x (quantity -1, price 100)

I'm having trouble generating the InvoiceDetail line without manually filling in all properties like this:

var newdetail = new InvoiceDetailEntity(); newDetail.Quantity = -1 * originalDetail.Quantity; newDetail.Price = originalDetail.Price; ... save newDetail to DB

The InvoiceDetailEntity contructor takes an IEntityFields2 parameter, so I thought I might be able to do

var newDetail = new InvoiceDetailEntity(originalDetail.Fields);

but when I save that, I get strange results, not indicating that a "shallow copy" is created. Am I approaching this correctly? What does that constructor overload actually do?

In my actual, real-world scenario things get more complicated, as InvoiceDetail actually refers to other items (multiple 1..n relations), so what I'm looking for is not necessarily a deep-copy/clone method for the entire object tree, but more of a way to avoid having to write tedious property to property assignment operations like the Quantity and Price examples above. I have found references to a clone strategy involving (de)serializing to a strem, but that seem to be kind of over-the-top for my needs simple_smile

Any help would be appreciated.

/Jan

MySQL version 5.6.43 LLBLGen version 5.6 (5.6.1) RTM DevArt version (latest express from their website - 8.16 apparently)

Walaa avatar
Walaa
Support Team
Posts: 14950
Joined: 21-Aug-2005
# Posted on: 14-Sep-2020 01:03:27   
var newDetail = new InvoiceDetailEntity(originalDetail.Fields);

This is used internally by the fetch pipeline, you can't use it.

You can try the following:

var clonedCustomer = new CustomerEntity { Fields = originalCustomer.Fields.Clone() };