0

我正在 MVC 中创建应用程序。当我尝试将数据插入 SQL Server 2008 时,它显示如下错误:

ObjectStateManager 中已存在具有相同键的对象。现有对象处于未更改状态。只有处于添加状态的对象才能再次添加到 ObjectStateManager。

这是什么意思?

      Candidate candidate = _repository.GetCandidate(LoggedInCandidate.Id);

            candidate.Name = collection["Name"];
            candidate.Email = collection["Email"];
            candidate.Address = collection["Address"];
            candidate.ContactNumber = collection["ContactNumber"];
            candidate.MobileNumber = collection["MobileNumber"];
            candidate.LicenseNumber = collection["LicenseNumber"];
            int candidateId = _repository.AddCandidate(candidate);
            string[] languages = collection["Languages"].Split(',');
         foreach (string language in languages)
         {
             if (!string.IsNullOrEmpty(language))
             {
                 CandidateLanguage cl = new CandidateLanguage();
                 cl.CandidateId = candidateId;
                 cl.LanguageId = Convert.ToInt32(language);
                 _repository.AddCandidateLanguage(cl);
             }
         }

           _repository.Save();
           }
4

2 回答 2

0

你已经得到了一个有 id 的候选人。你为什么要把这个候选人再次插入到上下文中???

如果要插入一个新的候选人,为什么要创建一个新的候选人并插入它。

于 2012-09-11T12:03:24.477 回答
0

如果您希望复制现有实体并在此之后只修改一些属性,您将需要一个复制构造函数(或具有类似想法的东西),然后将新实体插入到数据库中。

如果你想修改你当前的候选人,你会做

        Candidate candidate = _repository.GetCandidate(LoggedInCandidate.Id);

        candidate.Name = collection["Name"];
        candidate.Email = collection["Email"];
        candidate.Address = collection["Address"];
        candidate.ContactNumber = collection["ContactNumber"];
        candidate.MobileNumber = collection["MobileNumber"];
        candidate.LicenseNumber = collection["LicenseNumber"];

        _repository.Entry(candidate).State = EntityState.Modified;

        ....

        _repository.Save();
于 2012-09-11T12:13:18.600 回答