使用EntityFramework更新记录时出错
本文关键字:出错 新记录 更新 EntityFramework 使用 | 更新日期: 2023-09-27 18:07:37
我想更新记录,但程序捕获此错误
ObjectStateManager中已经存在具有相同key的对象。ObjectStateManager不能跟踪具有相同键的多个对象。"
This Is My Codes
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);
}
}
And This Is My Update Method In UserDa Class
public bool Update(PortalEntities contextEntities, User item)
{
var res = contextEntities.SaveChanges() > 0;
return res;
}
为什么显示错误以及如何修复它
我相信Igor是正确的。要解决此问题,当用户已经存在于数据库中时,则更新用户属性而不是项属性。删除"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);
}
}