问题描述
我正在编写一个简单的博客应用程序并尝试在我的通用存储库模式中建立 CRUD 操作,但我的更新方法出现错误:
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:
'System.Data.Entity.DbSet' 不包含对'Entry' 并且没有扩展方法 'Entry' 接受第一个参数可以找到类型System.Data.Entity.DbSet"(您是否缺少使用指令还是程序集引用?)
'System.Data.Entity.DbSet' does not contain a definition for 'Entry' and no extension method 'Entry' accepting a first argument of type 'System.Data.Entity.DbSet' could be found (are you missing a using directive or an assembly reference?)
我关注了 帖子通过在 DbContext 上添加额外的间接级别来伪造"Entry().但是在 MVC 5 中,我们继承自:IdentityDbContext,而不是 DbContext.我确实尝试实施作者的修复,但错误仍然存在.
I followed a post that explained how to 'fake' Entry() by adding additional level of indirection over DbContext. However in MVC 5 we're inheriting from: IdentityDbContext and not DbContext. I did try implementing the authors fix but the error persists.
如何使用 IdentityDbContext 在 Entity Framework 6 中向我的存储库添加更新方法?如果我们不应该这样做,那么如何使用这种模式更新记录?
How can I add an update method to my repository in Entity Framework 6 using IdentityDbContext? If we aren't supposed to do it this way then how do I update a record with this pattern?
我应该注意,所有其他方法都按预期工作.
I should note that all other the other methods work as expected.
我的通用存储库:
public class BlogEngineRepository<T> : IRepository<T> where T : class
{
protected DbSet<T> DbSet;
public BlogEngineRepository(DbContext dataContext)
{
DbSet = dataContext.Set<T>();
}
#region IRepository<T> 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<T> SearchFor(Expression<Func<T, bool>> predicate)
{
return DbSet.Where(predicate);
}
public IQueryable<T> GetAll()
{
return DbSet;
}
public T GetById(int id)
{
return DbSet.Find(id);
}
#endregion
}
推荐答案
更新应该看起来像(扩展 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.
这篇关于使用带有实体框架 6 的存储库模式更新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!