0

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!

Anonim
  • 61
  • 1
  • 13
  • What does GetListById look like? Chances are it is loading the entities into the context, therefore attaching them again to the same context will cause an error. – Anthony Chu Jul 08 '14 at 05:32
  • i already update code for GetListById , and can you more explain what i do for fixed this.. – Anonim Jul 08 '14 at 05:49
  • What happens if you just call SaveChanges without trying to Attach or SetEntityState? If EF already knows about your entity, you should be able to just save it. – Alex Edelstein Aug 24 '14 at 17:25
  • 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 13:10

1 Answers1

0

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

Anonim
  • 61
  • 1
  • 13