1

我是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()
}
4

0 回答 0