Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is accepted answer to this question <a href="https://stackoverflow.com/questions/899734/strongly-typed-asp-net-mvc-with-entity-framework">Strongly-Typed ASP.NET MVC with Entity Framework</a></p> <pre><code>context.AttachTo(product.GetType().Name, product); ObjectStateManager stateMgr = context.ObjectStateManager; ObjectStateEntry stateEntry = stateMgr.GetObjectStateEntry(model); stateEntry.SetModified(); context.SaveChanges(); </code></pre> <p>Have you tried out that?</p> <p><strong>[Updated, code on top does not work]</strong></p> <p>This is small extension property I used so next code block is easier to understand:</p> <pre><code>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() &gt; 0) return (int)CategoryReference.EntityKey.EntityKeyValues[0].Value; else return null; } } } </code></pre> <p>and that worked for me (this time for sure):</p> <pre><code>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 &amp;&amp; ((EntityObject)originalItem).EntityState != System.Data.EntityState.Added) { Product origProduct = originalItem as Product; origProduct.CategoryID == product.CategoryID;//set foreign key again to change the relationship status context.ApplyPropertyChanges( key.EntitySetName, product); } }context.SaveChanges(); </code></pre> <p>For sure it's looks hacky. I think that the reason is because the EF relationships have status as entities (modified, added, deleted) and based on that status EF changes the value of foreign keys or deletes row if many to many relationship is in case. For some reason (don't know why) the relationship status is not changed the same as property status. That is why I had to set the CategoryReference.EntityKey on originalItem in order to change the status of the relationship.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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