1

In my model I have two classes Categories and Products. There is a relation many- to many between them.

I set states of all categories on modified manually and when I watched in the debugger before saveChanges() I saw that all of these categories were marked as modified. But after request mapping between categories and product weren't updated in my database. Code of update function.

public void UpdateProduct(Product product) 
    {
        using (EFDbContext context = new EFDbContext())
        {
            context.Products.Attach(product);
            if (product.Categories != null)
            {
                foreach (var item in product.Categories)
                {
                    context.Entry(item).State = EntityState.Modified;
                }
            }
            context.Entry(product).State = EntityState.Modified;

            context.SaveChanges();
        }
    }
Malv20
  • 159
  • 4
  • 11

1 Answers1

2

Setting entity to modified says that you have changed its properties (not navigation properties) and you want to save them. If you changed relations (navigation properties) by for example creating new relation between existing product and category or removing relation between existing product and category setting state to modified will not help you. This is actually very hard to solve (it is same in all current EF versions) because that relation has its own state which must be set and state of relation cannot be Modified = you must know if you added or removed relation. Especially removing is hard because you probably don't have information about relations you have removed from Categories navigation property when you are going to attach entity to the context. Moreover DbContext doesn't offer access to state of the relation so you must convert it to ObjectContext and use ObjectStateManager.

The easiest way to solve this issue is to load product with categories from database prior to saving and manually synchronize your detached object graph (the one you are trying to save at the moment) with loaded attached graph. Once you synchronize all changes in attached graph you will save it back to database. Attached graph will know which relations to categories were added or removed.

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670