且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用带有实体框架 6 的存储库模式更新记录

更新时间:2023-02-13 16:12:48

更新应该看起来像(扩展 Dan Beaulieu 的回答) :

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 如下所示:

public class BlogEngineRepository<T> : IRepository<T> where T : class
{
  public BlogEngineRepository(DbContext dataContext)
  {
    DbSet = dataContext.Set<T>();
    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.