【发布时间】:2011-10-06 18:47:42
【问题描述】:
我正在使用this link 的示例按照存储库和工作单元模式更新 SQL Server 2008 中的数据库表。
虽然我已经让插入工作。我很难让更新和删除工作。更新没有错误,也不会更新。删除会给出这样的 InvalidOperationException The object cannot be deleted because it was not found in the ObjectStateManager.
对于插入和删除,我使用示例中给出的 IObjectSet 方法。对于更新,我使用了 IObjectSet.Attach(entity) 方法,我将修改后的对象发送到该方法。
以下存储库和工作单元类的代码:
存储库类
命名空间数据访问 {
public interface IGenericRepository<T> where T : class { void AddRow(T entity); void UpdateRow(T entity); void Delete(T entity); } public abstract class GenericRepository<T> : IGenericRepository<T> where T : class { protected IObjectSet<T> _objectSet; public GenericRepository(ObjectContext Context) { _objectSet = Context.CreateObjectSet<T>(); } public void AddRow(T entity) { _objectSet.AddObject(entity); } public void UpdateRow(T entity) { _objectSet.Attach(entity); } public void Delete(T entity) { _objectSet.DeleteObject(entity); } } }
工作单元类
namespace DataAccess
{
public interface IUnitOfWork
{
IGenericRepository<User> Users { get; }
void Commit();
}
public class UnitOfWork : IUnitOfWork
{
private readonly ObjectContext _context;
private UserRepository _userRepository;
public UnitOfWork(ObjectContext Context)
{
if (Context == null)
{
throw new ArgumentNullException("Context wasn't supplied");
}
_context = Context;
}
public void Commit()
{
_context.SaveChanges();
}
public IGenericRepository<User> Users
{
get
{
if (_userRepository == null)
{
_userRepository = new UserRepository(_context);
}
return _userRepository;
}
}
}
}
最后这就是我在调用代码中使用它进行更新的方式
public void UpdateUser(UserData userData)
{
using (mEntities context = new mEntities())
{
UnitOfWork uow = new UnitOfWork(context);
User usr = new User(); //This is the Entity Framework class
usr.ID = userData.RowID;
usr.UserName = userData.Username; //usr.UserName is the primary key in the table
uow.Users.UpdateRow(usr);
uow.Commit();
}
}
但是更新没有发生。我在这里做错了什么?我正在使用带有 EF 4 的 VS2010
感谢您的宝贵时间...
【问题讨论】:
标签: c# entity-framework domain-driven-design repository-pattern unit-of-work