【发布时间】:2016-09-20 05:28:54
【问题描述】:
我想更新一条记录,但程序发现了这个错误
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;
}
为什么会显示错误以及如何修复它?
【问题讨论】:
-
可能是因为实例
item已被跟踪,现在您正在检索或添加重复的实例到行var user = new UserDa().Get(ContextEntities, item.Id);//get current user。只是猜测,因为您没有提供此方法的代码。
标签: c# asp.net-mvc entity-framework