有时候用这个方法,没办法Attach对象。
using (var db = new DBContextEntities())
{
db.Attach((IEntityWithKey) entity);
db.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
result = db.SaveChanges() > 0;
}
暂时还不清楚为什么有时候在页面上用这个attach去附加获得的model的时候不能找到他的EntityKey,猜大概返回获得的那个对象是需要获得EntityKey的,但页面上没有给(也没办法传啊···)。
而在做WinFrom的时候,用gridview那些控件能够直接获得本身的所有状态,所以能行。
于是解决这个的办法就是手动把对象添加到上下文:
using (var db = new DBContextEntities())
{
db.CreateObjectSet<T>().AddObject(entity);
db.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
result = db.SaveChanges() > 0;
}
你可以试试