我使用的是例如關閉this link更新工作模式的存儲庫和單位按照SQL Server 2008數據庫表。實體框架CreateObjectset安裝方法不更新
雖然我已經得到了插入工作。我很難得到更新並刪除工作。更新不會發生錯誤,並且不會更新。刪除給出這樣的InvalidOperationException The object cannot be deleted because it was not found in the ObjectStateManager.
對於插入和刪除我正在使用示例中給出的IObjectSet方法。對於更新,我使用IObjectSet.Attach(實體)方法向其發送修改後的對象。
代碼庫及以下工作類單位:
倉儲類
命名空間數據訪問{
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個
感謝您的時間...
改變了我的資料庫中刪除方法現在讀作... _objectSet.Attach(實體); _context.ObjectStateManager.ChangeObjectState(實體,System.Data.EntityState.Deleted); _objectSet。DeleteObject的(實體); – user20358
這也沒有幫助.. – user20358
而錯誤信息是一樣的,它被扔在哪裏?當你可以設置對象的狀態時,我認爲它也會在稍後找到對象。至少更新是否工作? – Andreas