entityframework clone or copy an entity instance to another object

asp.net-core-mvc entity-framework entity-framework-core

Question

I am working on an asp.net mvc core 2.0 project and entityframework.

I am working with viewmodel concept.

This mean i do not pass entities instances directly to my view, i pass a viewmodel instance which only contains what the view needs.

in one case, i need to pass the entire entity fields plus other informations.

What i've done is a derivated my ViewModel class from my Entity Class. and i add the extra fields:

public MyViewModel: Person
{
    // I will automaticly have Person fields in MyViewModel
    public bool IsSelected {get;set;}
    public String otherinformation {get;set;}
    ...
}

I am fed up with assigning each fields of my viewmodel from my entity instance.

myviewmodelinstance.field1 = myentity.field1;
myviewmodelinstance.field2 = myentity.field2;
myviewmodelinstance.field3 = myentity.field3;
myviewmodelinstance.IsSelected = false;
...

And i need to do the inverse operation in the postback.

Is there a way to "copy" or "clone" every fields, like this:

myentity.CopyTo(myviewmodelinstance);
myviewmodelinstance.IsSelected = false;

Thanks

1
0
12/15/2017 8:53:08 PM

Popular Answer

You could use the AutoMapper to achieve it. It is the ideal way to perform it. Another option is that you can serialize and deseriliaze the object as json.

var myviewmodelinstance = JsonConvert.DeserializeObject<MyViewModel>(JsonConvert.SerializeObject(myentity));

Note : The code I provided required Json.Net

0
12/16/2017 8:12:56 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow