c# - Attaching a deattached object to context -


i've got application in ui can add categories exist in db product , post backend.

but when try save below (try 1 , 2), not save attached categories database.

what missing?

 public bool saveproduct(product product)   {     //try 1     foreach(var item in product.categories) {             db.entry(item).state = item.id == 0 ?                 entitystate.added :                 entitystate.modified;         }     //try 2     foreach(category category in product.categories) {         db.entry(category).state = entitystate.modified;         db.category.attach(category);     }     return save(); }  public class product {     public int id { get; set; }     public string title { get; set; }     public list<category> categories { get; set; } }  public class category {     public int id { get; set; }     public string name { get; set; }  } 

the order problem.

first set entry of category object in context modified (which should retrieve object same concurrencytokens database , set state modified), , attach current object context (obviously in unchanged state).

this override first call and, since no entries modified or added, not persisted in database.

try reversing order of attach() , state=modified.


Comments