4

I have the 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 as expected.. Sometimes. Other times I get this error message:

{"Attaching an entity of type 'DataAccess.Plusbog.C_Category' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate."}

This even though I feel that's pretty much what I try to avoid looking for the entity in the changetracker. I feel like I've tried every solution I could find, but nothing works :-/

Any help would be appreciated :-)

Nicholas Magnussen
  • 769
  • 2
  • 9
  • 26
  • You might have a look at my answer on [ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value](http://stackoverflow.com/questions/23201907/asp-net-mvc-attaching-an-entity-of-type-modelname-failed-because-another-ent/39557606#39557606). – Murat Yıldız Sep 18 '16 at 12:28

2 Answers2

0

Examine closely navigation properties of the entities you're attaching: categories might have Books property which have other books which in their turn have other categories. EF will traverse the whole graph and attach every entity it can reach creating the aforementioned problem. Try blanking some navigation properties which you don't need processed.

I bet you are having this exception while saving the list of books which have one or more categories in common.

Maxim Balaganskiy
  • 1,524
  • 13
  • 25
0

I solved this by attaching my models to a freshly instantiated context and then saving the changes to that one. This points to the fact that I'm retrieving data about books and categories using different contexts and then trying to save the changes to yet another context.

Nicholas Magnussen
  • 769
  • 2
  • 9
  • 26