1

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!

Johan
  • 35,120
  • 54
  • 178
  • 293
  • 1
    Check out `Clone` - http://stackoverflow.com/questions/78536/cloning-objects-in-c-sharp – Lloyd Powell Dec 21 '11 at 14:07
  • take a look at http://weblogs.asp.net/zeeshanhirani/archive/2010/05/24/how-to-share-common-fields-between-two-entities-that-map-to-different-tables.aspx – Glory Raj Dec 21 '11 at 14:09

2 Answers2

2

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

Garrett Vlieger
  • 9,354
  • 4
  • 32
  • 44
2

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

shenhengbin
  • 4,236
  • 1
  • 24
  • 33