I'm following the Sports Store example in Pro ASP.NET MVC Framework and I'm getting an exception related to LINQ that I cannot figure out. The full code is available through the website but here is a snippet to convey the problem.
private Table<Product> productsTable;
// ...
public void SaveProduct(Product product) {
if (product.ProductID == 0)
productsTable.InsertOnSubmit(product);
else {
productsTable.Attach(product);
productsTable.Context.Refresh(RefreshMode.KeepCurrentValues, product);
}
productsTable.Context.SubmitChanges();
}
In the UI, I update an existing product and click save and the controller handles the post by calling SaveProduct(product) - where product is passed via parameter. A DuplicateKeyException is thrown upon attaching product. In the debugger, the product parameter is initialized and has an ID of 2.
I don't expect an exact answer but I'm hoping that someone can give me some hints as to where I can look to address this problem.
UPDATE: The following code works, but I'm still hoping to get the attach method above working.
public void SaveProduct(Product product) {
if (product.ProductID == 0)
productsTable.InsertOnSubmit(product);
else {
Product p2 = productsTable.Single(em => em.ProductID == product.ProductID);
p2.Name = product.Name;
p2.Description = product.Description;
p2.Price = product.Price;
p2.Category = product.Category;
}
productsTable.Context.SubmitChanges();
}