Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The reason this fails is two fold.</p> <ol> <li>In order to update a Reference (i.e. Product.Category) you have to have the original reference value in the context too.</li> <li>ApplyPropertyChanges(...) only applies to regular / scalar properties of the Entity, the reference is left unchanged</li> </ol> <p>So I would do something like this (Note this code makes heavy use of a trick called <a href="http://blogs.msdn.com/alexj/archive/2009/06/19/tip-26-how-to-avoid-database-queries-using-stub-entities.aspx" rel="nofollow noreferrer">stub entities</a> to avoid mucking around with EntityKeys)</p> <pre><code>Product product = new Product(); // Use a stub because it is much easier. product.Category = new Category {CategoryID = selectedCategoryID}; product.Name = txtName.Text.Trim(); ... other properties StockControlDAL.EditProduct(productId, originalCategoryID); public static void EditProduct(Product product, int originalCategoryID ) { using(var context = new ShopEntities()) { // Attach a stub entity (and stub related entity) var databaseProduct = new Product { ProductID = product.ProductID, Category = new Category {CategoryID = originalCategoryID} }; context.AttachTo("Products", databaseProduct); // Okay everything is now in the original state // NOTE: No need to call AcceptAllChanges() etc, because // Attach puts things into ObjectContext in the unchanged state // Copy the scalar properties across from updated product // into databaseProduct in the ObjectContext context.ApplyPropertyChanges("ShopEntities.Products", product); // Need to attach the updated Category and modify the // databaseProduct.Category but only if the Category has changed. // Again using a stub. if (databaseProduct.Category.CategoryID != product.Category.CategoryID) { var newlySelectedCategory = new Category { CategoryID = product.Category.CategoryID }; context.AttachTo("Categories", newlySelectedCategory) databaseProduct.Category = newlySelectedCategory; } context.SaveChanges(); } } </code></pre> <p>This will do the job, assuming no typos etc.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload