Linq to Sql Updates

  • Thread starter Thread starter ozy
  • Start date Start date
O

ozy

In all the samples that I have seen to update a table using Linq to
Sql, this is the type of code given:

public static void UpdateProduct()
{
NorthwindDataContext db = new NorthwindDataContext();

var product = db.Products.Single(p => p.ProductID == 1);

product.#PropertyName# = #NewValue#

db.SubmitChanges();
}

In the "real world", a Product would be retrieved and sent to the
client (say using WCF), the client would make a change to one or more
properties, and would then pass back the Product to the server. So, my
question is what code is required to save the Product back to the
database?

I can see that the following would work but there must be a better
way...

public static void UpdateProduct(Product updatedProduct)
{
NorthwindDataContext db = new NorthwindDataContext();

var product = db.Products.Single(p => p.ProductID == 1);

product.#Property1# = updatedProduct.#Property1#
product.#Property2# = updatedProduct.#Property2#
product.#Property3# = updatedProduct.#Property3#
product.#Property4# = updatedProduct.#Property4#
product.#Property5# = updatedProduct.#Property5#
product.#Property6# = updatedProduct.#Property6#
db.SubmitChanges();
}

Is there a way to link the passsd in Product with the DataContext and
therefore just call SubmitChanges without having to re-query the
database first?

Thanks in advance
 
Hi Ozy try:

public static void UpdateProduct(Product updated)
{
NorthwindDataContext db = new NorthwindDataContext();

var orig = db.Products.Single(p => p.ProductID ==
updated.ProductID);

db.Products.Attach(updated, orig);

db.SubmitChanges();
}
HTH jd
 
Back
Top