使用具有entity framework6的存储库模式更新记录

我正在编写一个简单的博客应用程序,并尝试在我的通用存储库模式中建立CRUD操作,但我的更新方法出现错误,说:

‘System.Data.Entity.DbSet’不包含’Entry’的定义,并且没有扩展方法’Entry’可以找到接受类型’System.Data.Entity.DbSet’的第一个参数(你是否缺少using指令)或汇编参考?)

我跟着一篇post解释了如何通过在DbContext上添加额外的间接级别来“伪造”Entry()。 但是在MVC 5中我们inheritance自: IdentityDbContext而不是DbContext。 我确实尝试实现作者修复,但错误仍然存​​在。

我的问题

如何使用IdentityDbContext将更新方法添加到Entity Framework 6中的存储库? 如果我们不应该这样做,那么如何使用这种模式更新记录?

我应该注意到其他所有方法都按预期工作。

我的通用存储库:

public class BlogEngineRepository : IRepository where T : class { protected DbSet DbSet; public BlogEngineRepository(DbContext dataContext) { DbSet = dataContext.Set(); } #region IRepository Members public void Insert(T entity) { DbSet.Add(entity); } public void Delete(T entity) { DbSet.Remove(entity); } public void Update(T entity) { DbSet.Entry(entity).State = System.Data.Entity.EntityState.Modified; } public IQueryable SearchFor(Expression<Func> predicate) { return DbSet.Where(predicate); } public IQueryable GetAll() { return DbSet; } public T GetById(int id) { return DbSet.Find(id); } #endregion } 

更新应该是这样的( 扩展Dan Beaulieu的回答 ):

 [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 : 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; } } 

您可以查看有关更新实体列表的有效方法的答案的完整说明,以获取有关更新详细信息的更多信息。

好的,我想出来了。 新存储库模式(entity framework6)中没有Update方法的原因是因为不需要一个 。 您只需按id获取记录,进行更改然后提交/保存。

例如,这是我的postController中的编辑POST方法:

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

RepositoryPattern看起来像这样:

 public class BlogEngineRepository : IRepository where T : class { protected DbSet DbSet; public BlogEngineRepository(DbContext dataContext) { DbSet = dataContext.Set(); } public void Insert(T entity) { DbSet.Add(entity); } public void Delete(T entity) { DbSet.Remove(entity); } public IQueryable SearchFor(Expression> predicate) { return DbSet.Where(predicate); } public IQueryable GetAll() { return DbSet; } public T GetById(int id) { return DbSet.Find(id); } }