保存数据库中的数据后将引发DbUpdateException

时间:2013-07-17 00:12:14

标签: asp.net asp.net-mvc

我有以下观点: -

@using (Ajax.BeginForm("AssignUsers", "SecurityGroup",
new AjaxOptions
{   HttpMethod = "POST",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "UsersAssignment"
}))
{
  @Html.HiddenFor(Model => Model.GroupID)
  @Html.AntiForgeryToken()
<span>Search</span>     <input  name="selectedUserNames" type="text" data-val="true" data-val-required= "Please enter a value."  data-autocomplete-source= "@Url.Action("AutoComplete", "SecurityGroup")" />
<span class="field-validation-valid" data-valmsg-for="selectedUserNames" data-valmsg-replace="true"></span>

<input type="submit" value="Assign" />
}

以及以下Action方法: -

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AssignUsers(int GroupID, string[] selectedUserNames, string[] currentUserNames)
        {
            try
            {
                if (ModelState.IsValid)
                {   repository.AssignUserGroup(GroupID, selectedUserNames, currentUserNames);
                    repository.Save();
                    if (!Request.IsAjaxRequest())
                    {
                        return RedirectToAction("Details", new { id = GroupID });
                    }
                    else if (Request.IsAjaxRequest())
                    {
                        var ADUsers = repository.GetADUsers();
                        var group = repository.FindAllGroup(GroupID);
                        ViewBag.Users = repository.populateAssignedUsersData(group, ADUsers); 
                        return PartialView("_Group", group);
                    }
                }
            }
            catch (DbUpdateException)
            {
                ModelState.AddModelError(string.Empty, "Error occured. User might already assinged.");
                var ADUsers = repository.GetADUsers();
                var group = repository.FindAllGroup(GroupID);
                ViewBag.Users = repository.populateAssignedUsersData(group, ADUsers);
                return PartialView("_Group", group);
            }
            return null;
        }

最后是存储库模型: -

public void AssignUserGroup(int id, string[] selectedUsers, string[] currentusernames)
        {   
            var usergroups = tms.UserGroups.Where(a=>a.GroupID == id);
            foreach (var ug in usergroups)
            {
                if (currentusernames != null)
                {
                    for (int c = 0; c < currentusernames.Count(); c++)
                    {
                        if (ug.UserName.ToUpper() == currentusernames[c].ToUpper())
                        {
                            tms.UserGroups.Remove(ug);
                        }
                    }
                }
            }
           if( selectedUsers !=null)
           { 
               for (int i = 0; i < selectedUsers.Count(); i++)
               {   
                   UserGroup usergroup = new UserGroup();
                   usergroup.GroupID = id;
                   usergroup.UserName = selectedUsers[i];
                   tms.UserGroups.Add(usergroup);
               }
           } 
       }

但奇怪的是,当用户单击Ajax.Begin表单来分配新用户时,该用户将被添加到数据库中,但同时会引发DBUpdateException并出现“错误”用户可能已经分配了。“模型状态错误将被显示。这是完整的错误描述: -

  

发现了System.Data.Entity.Infrastructure.DbUpdateException   HResult = -2146233087消息=更新时发生错误   条目。有关详细信息,请参阅内部异常来源=的EntityFramework   堆栈跟踪:          在System.Data.Entity.Internal.InternalContext.SaveChanges()          在System.Data.Entity.Internal.LazyInternalContext.SaveChanges()          在System.Data.Entity.DbContext.SaveChanges()          在C:\ Users \ Administrator \ Documents \ Visual Studio中的TMS.Models.Repository.Save()   2012 \ Projects \ TMS \ TMS \ Models \ Repository.cs:第60行          at TMS.Controllers.SecurityGroupController.AssignUsers(Int32 GroupID,String [] selectedUserNames,String [] currentUserNames)in   c:\ Users \ Administrator \ Documents \ Visual Studio   2012 \ Projects \ TMS \ TMS \ Controllers \ SecurityGroupController.cs:第98行   InnerException:System.Data.UpdateException          的HResult = -2146233087          消息=更新条目时发生错误。有关详细信息,请参阅内部异常          来源= System.Data.Entity的          堆栈跟踪:               在System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager)   stateManager,IEntityAdapter适配器)               在System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager   entityCache)               在System.Data.Objects.ObjectContext.SaveChanges(SaveOptions选项)               在System.Data.Entity.Internal.InternalContext.SaveChanges()          InnerException:System.Data.SqlClient.SqlException               的HResult = -2146232060               消息=违反PRIMARY KEY约束'PK_UserGroup'。无法在对象中插入重复键   'dbo.UserGroups'。重复键值为(44,testuser)。该   声明已经终止。               Source = .Net SqlClient数据提供程序               错误码= -2146232060               类= “14”               LineNumber上= 1               数= 2627               过程=“”               服务器= WIN-SPDEV               状态= 1               堆栈跟踪:                    在System.Data.SqlClient.SqlConnection.OnError(SqlException异常,   Boolean breakConnection,Action 1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action 1 wrapCloseInAction)                    在System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject)   stateObj,Boolean callerHasConnectionLock,Boolean asyncClose)                    在System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,SqlCommand cmdHandler,SqlDataReader dataStream,   BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject   stateObj,布尔&amp; dataReady)                    在System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,   RunBehavior runBehavior,String resetOptionsString)                    在System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior   cmdBehavior,RunBehavior runBehavior,Boolean returnStream,Boolean   async,Int32超时,任务&amp; task,Boolean asyncWrite)                    在System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior   cmdBehavior,RunBehavior runBehavior,Boolean returnStream,String   方法,TaskCompletionSource 1 completion, Int32 timeout, Task& task, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource 1   completion,String methodName,Boolean sendToPipe,Int32 timeout,   布尔asyncWrite)                    在System.Data.SqlClient.SqlCommand.ExecuteNonQuery()                    在System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator)   翻译器,EntityConnection连接,字典2 identifierValues, List 1 generatedValues)                    在System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager)   stateManager,IEntityAdapter适配器)               的InnerException:

请问我的代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

  

请问我的代码出了什么问题?

您的例外情况明确指出:

  

违反PRIMARY KEY约束'PK_UserGroup'。无法在对象'dbo.UserGroups'中插入重复键。重复键值为(44,testuser)。

由于我不知道您的PK_UserGroup是什么,所有人都可以说您不应该将重复的主键值插入到表dbo.UserGroups中。

你的两个选择是;检查是否存在具有重复键的记录并执行错误处理,或者(不推荐)捕获PK_UserGroup的数据库异常并执行错误处理。