Johan
Johan

Reputation: 35194

Mapping property values between 2 entities

Lets say i have 2 instances of my entities, A and B. I want to map each value from entity A over to entity B. At the moment im doing something similar to

A.firstprop = B.firstprop;
A.secondprop = B.secondprop;

etc.. Im not sure how to solve this in a loop, so i would like some assistance on that part. Thanks!

Upvotes: 1

Views: 187

Answers (2)

shenhengbin
shenhengbin

Reputation: 4294

For your question : How to solve it in the loop is like

        var e1 = new Entity();
        var e2 = // Get Entity 

        foreach (var p in e1.GetType().GetProperties())
        { 
            p.SetValue(e1 , e2.GetType().GetProperty(p.Name ).GetValue(e2 , null) , null );
        }

So that , you can copy the value from entity2 to entity1 by looping

Upvotes: 2

Garrett Vlieger
Garrett Vlieger

Reputation: 9494

You should consider using the Automapper library. This will simplify having to write all of the mappings by hand.

Upvotes: 2

Related Questions