3

我正在使用通用存储库和工作单元,不知道为什么它不会检测到我对数据库所做的更改。

public abstract class Repository<T> : IRepository<T>
    where T : class, IAuditEntity
{
    protected IObjectSet<T> _objectSet;

    public Repository(ObjectContext context)
    {
        _objectSet = context.CreateObjectSet<T>();
    }

    #region IRepository<T> Members

    public abstract T GetById(object id);

    public IEnumerable<T> GetAll()
    {
        return _objectSet.Where(e => !e.IsDeleted).OrderByDescending(o => o.ModifiedOn);
    }

    public IEnumerable<T> Query(Expression<Func<T, bool>> filter)
    {
        return _objectSet.Where(filter);
    }

    public void Add(T entity)
    {
        _objectSet.AddObject(entity);
    }

    public void Update(T entity)
    {
       //some code here; not working
       //What do I need to put here?
    }

    public void Remove(T entity)
    {
        _objectSet.DeleteObject(entity);
    }
}

控制器:

[HttpPost]
    public ActionResult Edit(Student stud)
    {
        if (ModelState.IsValid)
        {
            _unitOfWork.Students.Update(stud);
            _unitOfWork.Commit();
            return RedirectToAction("Index");
        }
        return View(stud);
    }

之前,我尝试使用以下方法更新我的记录:

[HttpPost]
    public ActionResult Edit(Student stud)
    {
        if (ModelState.IsValid)
        {
            var i = _unitOfWork.Students.GetById(stud.StudentID);
            TryUpdateModel(i);
            _unitOfWork.Commit();
            return RedirectToAction("Index");
        }
        return View(stud);
    }

当然可以,但我确信这不是正确的方法。只是想问我需要什么才能使我的存储库上的 Update 方法工作?

4

2 回答 2

3

您需要保留对存储库中上下文的引用并使用它:

public void Update(T entity)
{
   _objectSet.Attach(entity);
   _context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
}
于 2013-03-01T12:13:58.260 回答
1

发生这种情况是因为当 Student 对象被回发到控制器时,由于 HTTP 的无状态特性,它不再附加到实体框架上下文。

您从数据库获取记录并对其进行修改的第二种方法很好,但显然涉及到数据库的额外往返。

I normally use Dbcontext rather than ObjectContext which I belive is essentially a wrapper around ObjectContext with some extra functionality. I'm not sure if this helps or not but if you were to use DbContext you would be able to do this....

dbContext.Entry(stud).State = EntityState.Modified;
dbContext.SaveChanges();

The same can be achieved through the ObjectContext by calling AttachTo to re-attach the returned Student back to the context and then set it's state to modified before you call SaveChanges.

于 2013-03-01T12:17:58.297 回答