我正在使用this link中的示例,按照存储库和工作单元模式更新SQL Server 2008中的数据库表。
当我使插入工作。我很难获取更新和删除的工作。此更新没有错误,也不会更新。删除给出一个像这样的InvalidOperationException The object cannot be deleted because it was not found in the ObjectStateManager.
对于插入和删除,我使用示例中给出的IObjectSet方法。对于Update,我使用IObjectSet.Attach(entity)方法,将修改后的对象发送到该方法。
下面的存储库和工作单元类代码:
储存库类
命名空间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();
}
}
但是更新不会发生。我在这里做错了什么?我正在将VS2010与EF 4配合使用
谢谢你的时间...
最佳答案
在UpdateRow
中附加项目后,需要将其标记为已修改。实体以“未更改”状态附加。但是,要修改状态,您需要访问ObjectStateManager
,这是上下文的属性。在EF 4.1 I was told中,上下文中有一个方法Entry()
允许您同时设置状态。
要删除实体,它必须存在于上下文中。如果尚未加载,则必须先附加它,然后再删除它。
还请注意使用new()
和CreateObject<T>()
之间的difference。
关于c# - Entity Framework CreateObjectset Attach方法未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7678987/