我正在使用 this link 的示例按照存储库和工作单元模式更新 SQL Server 2008 中的数据库表。
虽然我已经让 Insert 工作了。我很难让更新和删除正常工作。更新没有报错,也不更新。删除给出了一个 InvalidOperationException 像这样 The object cannot be deleted because it was not found in the ObjectStateManager.
对于插入和删除,我使用示例中给出的 IObjectSet 方法。对于更新,我使用 IObjectSet.Attach(entity) 方法将修改后的对象发送到该方法。
以下存储库和工作单元类的代码:
存储库类
namespace DataAccess {
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
感谢您的宝贵时间...
最佳答案
在 UpdateRow
中附加项目后您需要将其标记为已修改。实体以未更改状态附加。但是,要修改状态,您需要访问 ObjectStateManager
这是上下文的属性。在 EF 4.1 I was told有一种方法 Entry()
在允许您设置状态的上下文中。
要删除一个实体,它必须存在于上下文中。如果尚未加载,您必须在删除之前附加它。
还要注意 difference在使用 new()
之间和 CreateObject<T>()
.
关于c# - Entity Framework CreateObjectset 附加方法不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7678987/