0

a problem crossed my way more than once.

I'm using a Linq DataClass in a DataContext. After a loader ran through this, its sometime needed to move an Object to another DataClass with the same structure.

So f.e. Products and ProductsHistory, each time after a change in Products, the actual Product is taken an put into ProductsHistory.

How can I simplify this action, without writing an conversion function like that:

private static ProductHistory convert(Product p)
    {
        ProductHistory ph = new ProductHistory();
        ph.Attr1 = p.Attr1;
        ph.Attr2 = p.Attr2;
        //...and hundreds like this on...
        return ph;
    }

I do not want to execute a SQL Query like DataContexts would support.

Any hint would be nice,

thanks in advance,

Harry

Harry
  • 1,313
  • 3
  • 22
  • 37

2 Answers2

1

Reflection would be only way to do it automatically

Through reflection you would have to explore all properties of source object. Find respective property of target object. Then copy the values

//pseudo-code 
//something like this 

TargetInstance target = new TargetInstance();

foreach(Property sourceProperty in sourceinstance)
{
    if(target contains sourceProperty)
    {
        target[SourceProperty] = sourceInstance[SourceProperty];
    }    
}

Take a look at this question it is similar to your scenario

Community
  • 1
  • 1
Haris Hasan
  • 29,856
  • 10
  • 92
  • 122
  • Is there no native feature? This problem can't be that uncommon(?). – Harry Jan 04 '12 at 15:16
  • No there is no native feature – Haris Hasan Jan 04 '12 at 15:18
  • @Harry - while it's not necessarily uncommon, keep in mind that this is really outside the scope of Linq. Furthermore, there are at least two other ways that this is commonly solved - SQL trigger or proc, or a custom constructor for class B that takes an instance of class A and copies the values. – GalacticCowboy Jan 04 '12 at 15:24
  • took [this](http://stackoverflow.com/questions/755646/setvalue-on-propertyinfo-instance-error-object-does-not-match-target-type-c-sh) out of StackOverflow(attention, code needs to be corrected like the given answer) and it works perfectly. Thanks guys! – Harry Jan 04 '12 at 16:58
0

I would consider using AutoMapper for this sort of thing...

IKEA Riot
  • 111
  • 2