This is an accepted answer to this question Strongly configured ASP.NET MVC with Entity Framework
context.AttachTo(product.GetType().Name, product); ObjectStateManager stateMgr = context.ObjectStateManager; ObjectStateEntry stateEntry = stateMgr.GetObjectStateEntry(model); stateEntry.SetModified(); context.SaveChanges();
Have you tried this?
[Updated, the code above does not work]
This is a small extension property that I used, so the following block of code is easier to understand:
public partial class Product { public int? CategoryID { set { CategoryReference.EntityKey = new EntityKey("ShopEntities.Categories", "CategoryID", value); } get { if (CategoryReference.EntityKey == null) return null; if (CategoryReference.EntityKey.EntityKeyValues.Count() > 0) return (int)CategoryReference.EntityKey.EntityKeyValues[0].Value; else return null; } } }
and it worked for me (this time for sure):
System.Data.EntityKey key = new System.Data.EntityKey("ShopEntities.Products", "ProductID", productId); object originalItem; product.EntityKey = key; if (context.TryGetObjectByKey(key, out originalItem)) { if (originalItem is EntityObject && ((EntityObject)originalItem).EntityState != System.Data.EntityState.Added) { Product origProduct = originalItem as Product; origProduct.CategoryID == product.CategoryID;
Surely it looks like hacks. I think the reason is that EF relationships have the status of entities (changed, added, deleted) and based on this status, EF changes the value of foreign keys or deletes a row if in any case there are many different relationships. For some reason (I donβt know why), the status of relations does not change in the same way as the status of a property. This is why I had to set CategoryReference.EntityKey to originalItem in order to change the relationship status.
Misha N. Oct. 23 '09 at 11:58 2009-10-23 11:58
source share