Search code examples
c#entity-frameworkupdatemodel

Update entity framework error key same value EF 6


I already make code in c# like this

IList<BookViewModel> ListBook= _bookService.GetListById(BookViewModel);
  foreach (BookViewModel apart in ListBook)
    {
    apart.Status = "Published";
    _bookService.Update(apart);
    }

and code update in my repository like this.

   public virtual TEntity Update(TEntity updatingObject)
        {
            this.GetDbSet<TEntity>().Attach(updatingObject);
            this.SetEntityState(updatingObject, EntityState.Modified);
            this.UnitOfWork.SaveChanges();
            return updatingObject;
        }

and my method

public IList<BookViewModel> GetListById(BookViewModel bookVM)
        {
            Expression<Func<Book, bool>> criteria = c => c.IdBook == bookVM.Id Book;

            return this.GetList(criteria);
        }

but i have error

Attaching an entity of type 'Models.Book' 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.

can any one have suggestion for change code update method, i already read many reference but it's different. thank's!


Solution

  • for this question i have some solution for update entity i use Entity framework extended.. this already in nugget..