实体框架附加错误:ObjectStateManager中已存在具有相同密钥的对象

时间:2012-05-21 22:01:01

标签: entity-framework asp.net-mvc-3 dbcontext

我是Entity Framework的新手,我已经查看了相同标题的问题,但我还没有找到令人满意的答案。

这是我的班级:

public class MyUser
{
 public string FirstName { get; set; }
public virtual ICollection<ProfileSkillEdu> Skills { get; set; }
}

在控制器中我有:

[HttpPost]
    public ActionResult EditProfile(MyUser user, string emailAddress)
    {
        try
        {
            if (ModelState.IsValid)
            {
                _unitOfWork.GetMyUserRepository().Update(user);
                _unitOfWork.Save();
                return View(user);
            }
        }
        catch (DataException)
        {
            //Log the error 
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
        }
        return View(user);
    }

在我的用户存储库中:

public virtual void Update(TEntity entityToUpdate)
    {
        dbSet.Attach(entityToUpdate);

        context.Entry(entityToUpdate).State = EntityState.Modified;

    }

我一直在 ObjectStateManager中已存在具有相同键的对象。 ObjectStateManager无法跟踪dbSet.Attach(entityToUpdate)中具有相同密钥的多个对象。。我看了变量,我发现如果MyUser只有1个Skill对象,那很好,因为当它执行Attach时,键是唯一的(值为0)。但是如果MyUser有2个技能对象,则两个主键的值都为0,因此错误。

有人可以解释为什么所有Skill对象的主键值都为0吗?此外,这个问题有一个简单的解决方案吗?我认为它应该是直截了当的,但我已经在这几个小时里苦苦挣扎。

编辑:

我想知道问题是否是因为我如何使用上下文。

在控制器定义中,我有:

public class MyAccountController : Controller
{
IUnitOfWork _unitOfWork;

 public ActionResult EditProfile()
    {
        if (_user == null)
        {
            MembershipUser currentUser = Membership.GetUser();

            if (currentUser == null)
            {
                return RedirectToAction("Logon", "Account");
            }
            Guid currentUserId = (Guid)currentUser.ProviderUserKey;

            MyUserService svc = new MyUserService();

            MyUser user = svc.GetUserLoaded(currentUserId); //this uses include/eager loading to get the Skills too.

            if (user == null)
            {
                return RedirectToAction("Logon", "Account");
            }
            else
                _user = user;
        }

        return View(_user);
    }
}

在我的UnitOfWork中,我有:

public class UnitOfWork:IUnitOfWork
{
    private GlobalContext context = new GlobalContext();

    private GenericRepository<MyUser> myUserRepository;
    private GenericRepository<Skill> skillRepository;

    .. and implementation of Save() and Dispose()
}

0 个答案:

没有答案
相关问题