Harry
Harry

Reputation: 1353

Linq-to-SQL Moving DataObject from one DataClass to another, keeping structure. Howto?

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

Upvotes: 0

Views: 271

Answers (2)

IKEA Riot
IKEA Riot

Reputation: 111

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

Upvotes: 0

Haris Hasan
Haris Hasan

Reputation: 30097

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

Upvotes: 1

Related Questions