我想更新记录,但程序会抓住此错误
ObjectStateManager中已存在具有相同键的对象。 ObjectStateManager无法使用相同的键跟踪多个对象。“
这是我的代码
public bool Update(User item, HttpPostedFileBase avatar)
{
var tran = ContextEntities.Database.BeginTransaction(IsolationLevel.ReadUncommitted);
try
{
var user = new UserDa().Get(ContextEntities, item.Id);//get current user
CheckConstraint(item, Enums.Status.Update);
//avatar checker
if (avatar != null)
{
if (avatar.ContentType != "image/jpeg")
throw new Exception("[Only Jpg Is Allowed");
if (user.AvatarId == null)
{
item.AvatarId = new FileDa().Insert(ContextEntities, avatar);
}
else if (user.AvatarId != null)
{
item.AvatarId = new FileDa().Update(ContextEntities, (Guid)user.AvatarId, avatar);
}
}
//password checker
item.Password = string.IsNullOrWhiteSpace(item.Password) ? user.Password : Utility.Hash.Md5(item.Password);
ContextEntities.Entry(item).State = EntityState.Modified;
if (!new UserDa().Update(ContextEntities, item))
throw new Exception();
tran.Commit();
return true;
}
catch (Exception ex)
{
tran.Rollback();
throw new Exception(ex.Message);
}
}
这是我在UserDa类中的更新方法
public bool Update(PortalEntities contextEntities, User item)
{
var res = contextEntities.SaveChanges() > 0;
return res;
}
为什么会出现错误以及如何解决?
答案 0 :(得分:0)
我相信伊戈尔是正确的。要解决此问题,当用户已存在于数据库中时,请更新用户属性,而不是项属性。删除代码行“ContextEntities.Entry(item).State = EntityState.Modified;”并保存更改。
public bool Update(User item, HttpPostedFileBase avatar)
{
var tran = ContextEntities.Database.BeginTransaction(IsolationLevel.ReadUncommitted);
try
{
var user = new UserDa().Get(ContextEntities, item.Id);//get current user
CheckConstraint(item, Enums.Status.Update);
if(user == null)
{
//throw and error or do something else
}}
//avatar checker
if (avatar != null)
{
if (avatar.ContentType != "image/jpeg")
throw new Exception("[Only Jpg Is Allowed");
if (user.AvatarId == null)
{
user.AvatarId = new FileDa().Insert(ContextEntities, avatar);
}
else if (user.AvatarId != null)
{
user.AvatarId = new FileDa().Update(ContextEntities, (Guid)user.AvatarId, avatar);
}
}
//password checker
user.Password = string.IsNullOrWhiteSpace(item.Password) ? user.Password : Utility.Hash.Md5(user.Password);
//ContextEntities.Entry(item).State = EntityState.Modified;
if (!new UserDa().Update(ContextEntities, user))
throw new Exception();
tran.Commit();
return true;
}
catch (Exception ex)
{
tran.Rollback();
throw new Exception(ex.Message);
}
}