views:

18

answers:

1

I am trying to merge data between two identical schema databases using Linq-to-sql:

List<Contact> contacts = (from c in oldDb.Contact
    select c).ToList();
contacts.ForEach(c => c.CreatedByID = 0);
newDb.Contact.InsertAllOnSubmit(contacts);
newDb.SubmitChanges();

Merely throws an "An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported." exception.

Other than doing the following, how else can this be done generically (in reasonable execution time):

List<Contact> contacts = (from c in oldDb.Contact
    select c).ToList();
contacts.ForEach(c => { c.CreatedByID = 0; newDb.Contact.InsertAllOnSubmit(contacts); });
newDb.SubmitChanges();

along with:

private t GetNewObject<t>(t oldObj)
{
    t newObj = (t)System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(typeof(t).Name);

    PropertyInfo[] props = typeof(t).GetProperties();
    foreach (PropertyInfo _prop in props)
    {
        _prop.SetValue(newObj, _prop.GetValue(oldObj, null), null);
    }
    return newObj;
}

The problem is this method is rather slow when there's only 11 objects and 75 properties, I need to do this for a couple hundred thousand objects so any performance gains I can get at this end would greatly reduce overall run time.

Basically, is there any Detach or similar call I could do that will disconnect the existing objects from the old DataContext and connect them to the new DataContext. Without having to create all new objects for each and every one of the returned rows.

A: 

I didnt got the

contacts.ForEach(c => { c.CreatedByID = 0; newDb.Contact.InsertAllOnSubmit(contacts); });

shouldnt be something like

contacts.ForEach(c => { 
    Contact c2 = GetNewObject<Contact>(c); 
    c2.CreatedByID = 0; 
    newDb.Contact.InsertOnSubmit(c2); 
});

also, here's a way of detaching the object from the old database: http://omaralzabir.com/linq_to_sql__how_to_attach_object_to_a_different_data_context/

bortao
Is there a way to do this generically, see my question here http://stackoverflow.com/questions/3952160/setting-entityreft-properties-to-default-using-reflection
Seph