c# - Getting or attaching an entity -


i have following method:

public bool removebookcategories(idictionary<books, ilist<c_category>> books)     {         _context.configuration.autodetectchangesenabled = true;          foreach (var book in books.keys)         {             foreach (var category in books[book])             {                 if (!_context.changetracker.entries<books>().any(e => e.entity.bookid == book.bookid))                     _context.books.attach(book);                 if (!_context.changetracker.entries<c_category>().any(e => e.entity.id == category.id))                     _context.c_category.attach(category);                  book.c_category.remove(category);             }         }          if (_context.savechanges() > 0)             return true;          return false;     } 

it works expected.. sometimes. other times error message:

{"attaching entity of type 'dataaccess.plusbog.c_category' failed because entity of same type has same primary key value. can happen when using 'attach' method or setting state of entity 'unchanged' or 'modified' if entities in graph have conflicting key values. may because entities new , have not yet received database-generated key values. in case use 'add' method or 'added' entity state track graph , set state of non-new entities 'unchanged' or 'modified' appropriate."}

this though feel that's pretty try avoid looking entity in changetracker. feel i've tried every solution find, nothing works :-/

any appreciated :-)

examine closely navigation properties of entities you're attaching: categories might have books property have other books in turn have other categories. ef traverse whole graph , attach every entity can reach creating aforementioned problem. try blanking navigation properties don't need processed.

i bet having exception while saving list of books have 1 or more categories in common.


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -