0

我有以下看法:-

@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" />
}

以及以下操作方法:-

[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 消息=更新条目时发生错误。有关详细信息,请参阅内部异常。Source=EntityFramework StackTrace:在 System.Data.Entity.Internal.InternalContext.SaveChanges() 在 System.Data.Entity.Internal.LazyInternalContext.SaveChanges() 在 System.Data.Entity.DbContext.SaveChanges() 在 TMS.Models。 c:\Users\Administrator\Documents\Visual Studio 2012\Projects\TMS\TMS\Models\Repository.cs 中的 Repository.Save():TMS.Controllers.SecurityGroupController.AssignUsers 的第 60 行(Int32 GroupID,String[] selectedUserNames, c:\Users\Administrator\Documents\Visual Studio 2012\Projects\TMS\TMS\Controllers\SecurityGroupController.cs:line 98 中的 String[] currentUserNames)
InnerException: System.Data.UpdateException HResult=-2146233087 消息=更新条目时出错。有关详细信息,请参阅内部异常。Source=System.Data.Entity StackTrace: 在 System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter 适配器) 在 System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache) 在 System.Data.Objects System.Data.Entity.Internal.InternalContext.SaveChanges() 处的 .ObjectContext.SaveChanges(SaveOptions 选项) InnerException:System.Data.SqlClient.SqlException HResult=-2146232060 消息=违反主键约束“PK_UserGroup”。无法在对象 'dbo. 用户组”。重复键值为 (44, testuser)。该语句已终止。Source=.Net SqlClient Data Provider ErrorCode=-2146232060 class="14" LineNumber=1 Number=2627 Procedure="" Server=WIN-SPDEV State=1 StackTrace: at System.Data.SqlClient.SqlConnection.OnError(SqlException 异常,布尔中断连接,动作1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 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 state&Obj, Boolean 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 timeout, Task& task , Boolean asyncWrite) 在 System.Data.SqlClient.SqlCommand。RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String 方法, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 完成,String methodName,Boolean sendToPipe,Int32 timeout,Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator 翻译器,EntityConnection 连接,字典2 identifierValues, List1生成值)在 System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager,IEntityAdapter 适配器)InnerException:

请对我的代码有什么问题有任何建议吗?

4

1 回答 1

0

请对我的代码有什么问题有任何建议吗?

您的例外明确指出:

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

因为我不知道你PK_UserGroup是什么,所以任何人都可以说你不应该在 table中插入重复的Primary Keydbo.UserGroups值。

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

于 2013-07-17T00:30:58.387 回答