views:

34

answers:

1

Let's say I created a new product like this:

Product p=new Product(){ Id= 2,Name="some name"};

My product variable has never been attached to a data context, how can I attach this entity so that my existing product in the database with Id=2 gets update with the name of my detached product?

A: 

I hope something similar would work

 Datacontext db = new Datacontext(); // replace with your DataContext
 Product originalProduct = 
         db.Products.Single(p => p.Id == 2); // get product with Id 2

 originalProduct.Name = "SomeName";  // only reset Name prop
 originalProduct = p;                // or you may assign p to originalProduct
 db.SubmitChanges();                 // submit changes to DB
Asad Butt
This should definitely work but could be painful to always copy over the properties. In NHibernate they have a construct called Reattach which would let you specify it's an existing object in the DB I'm not sure of L2S has this or not.
Chris Marisic
sure, but op is using L2S
Asad Butt