I have an entity with a collection of related entities.
I create a new entity with the same key, and new related entities (collection).
I've added the ned related entities to the collection of the main entity and now I want to save everything to the DB.
I've found the old entity and it's collection and detached everything. than i've attached the new entity and in foreach loop - all the related entities in the collection.
when I commit - context.SaveChanges() I get OptimisticCuncurrencyException Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
Any Ideas ?
code:
var old = (from c in context.Category.Include("Products").Where(x => (x.CatID== CatID) select c).FirstOrDefault();
if (old != null)
{
context.Detach(old);
foreach (Product stwp in old.Products)
{
context.Product.Detach(stwp);
}
}
context.Category.Attach(st);
context.ObjectStateManager.ChangeObjectState(st, System.Data.EntityState.Modified);
foreach (Product stwp in st.Products)
{
context.Product.Attach(stwp);
context.ObjectStateManager.ChangeObjectState(stwp, System.Data.EntityState.Modified);
}
context.SaveChanges();