Updating records using a Repository Pattern with Entity Framework 6

前端 未结 2 843
半阙折子戏
半阙折子戏 2020-12-29 07:43

I\'m writing a simple blog application and trying to establish CRUD operations in my generic repository pattern but I\'m getting an error on my update method that says:

2条回答
  •  情深已故
    2020-12-29 08:33

    Update should look like (expanding on Dan Beaulieu's answer) :

    [HttpPost]
    [ValidateAntiForgeryToken]
    [ValidateInput(false)]
    public ActionResult Edit([Bind(Include = "Id,Title,IntroText,Body,Modified,Author")] Post post)
    {
        using (UnitOfWork uwork = new UnitOfWork())
        {
            post.Modified = DateTime.Now;
            uwork.PostRepository.Update(post);
    
            uwork.Commit();
    
            return RedirectToAction("Index");
        }
    }
    

    RepositoryPattern looks like this:

    public class BlogEngineRepository : IRepository where T : class
    {
      public BlogEngineRepository(DbContext dataContext)
      {
        DbSet = dataContext.Set();
        Context = dataContext;
      }
    
      public T Update(T entity)
      {
         DbSet.Attach(entity);
         var entry = Context.Entry(entity);
         entry.State = System.Data.EntityState.Modified;
      }
    }
    

    You can view a full explaination to the answer for Efficient way of updating list of entities for more information on the details of just an update.

提交回复
热议问题