简体   繁体   English

使用EntityFramework更新记录时出错

[英]Error When Updating A Record With EntityFramework

I Want To Update A Record But Program Catch This Error 我想更新一条记录,但程序会捕获此错误

An object with the same key already exists in the ObjectStateManager. 具有相同键的对象已存在于ObjectStateManager中。 The ObjectStateManager cannot track multiple objects with the same 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 这是我在UserDa类中的更新方法

public bool Update(PortalEntities contextEntities, User item)
{
    var res =  contextEntities.SaveChanges() > 0;
    return res;
}

Why The Error Shown And How Can I Fix It ? 为什么显示错误,我该如何解决?

I believe that Igor is correct. 我相信伊戈尔是正确的。 To fix the issue, when the user already exist in the database then update the user properties and not the item properties. 若要解决此问题,请在用户已经存在于数据库中时更新用户属性,而不是项目属性。 Remove the line of code "ContextEntities.Entry(item).State = EntityState.Modified;" 删除代码行“ ContextEntities.Entry(item).State = EntityState.Modified;”。 and save the changes. 并保存更改。

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM