此错误在这里很普遍,但我在这里有不同的情况。我有表链接。我的部门表中有数据,所以外键存在。
这是错误:
INSERT语句与FOREIGN KEY约束“ FK_dbo.AspNetUsers_dbo.Department_Department_Id”冲突。在数据库“ aspnet-hr_pcms-20181109102923”的表“ dbo.Department”的列“ Department_Id”中发生了冲突。
源错误:
第153行:{
第154行:var user = new ApplicationUser {UserName = model.Email,Email = model.Email};
第155行:var结果=等待UserManager.CreateAsync(user,model.Password);
第156行:if(成功)
第157行:{
主要错误在第155行
堆栈跟踪:
[SqlException(0x80131904):INSERT语句与FOREIGN KEY约束“ FK_dbo.AspNetUsers_dbo.Department_Department_Id”发生冲突。在数据库“ aspnet-hr_pcms-20181109102923”的表“ dbo.Department”的列“ Department_Id”中发生了冲突。
System.Data.SqlClient.SqlConnection.OnError(SqlException异常,布尔值breakConnection,操作
1 wrapCloseInAction) +2555674 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action
1 wrapCloseInAction)+5958364 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj,布尔调用方HasConnectionLock,布尔asyncClose)+285 System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,SqlCommand cmdHandler,SqlDataReader dataStream,BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject stateObj,Boolean&dataReady)+4169 System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,RunBehavior runBehavior,字符串resetOptionsString,布尔值isInternal,布尔值forDescribeParameterEncryption,布尔值shouldCacheForAlwaysEncrypted)+255 System.Data.SqlClient.SqlCommand.CompleteAsyncExecuteReader(Boolean isInternal,Boolean forDescribeParameterEncryption)+262 System.Data.SqlClient.SqlCommand.InternalEndExecuteNonQuery(IAsyncResult asyncResult,String endMethod,Boolean isInternal)+652 System.Data.SqlClient.SqlCommand.EndExecuteNonQueryInternal(IAsyncResult asyncResult)+245 System.Data.SqlClient.SqlCommand.EndExecuteNonQueryAsync(IAsyncResult asyncResult)+156 System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult iar, Func
2 endFunction,Action1 endAction, Task
1个承诺,布尔值requireSynchronization)+86 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)+99 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)+58 System.Data.Entity.Utilities.CultureAwaiter`1.GetResult()+38 System.Data.Entity.Core.Mapping.Update.Internal.d__0.MoveNext()+2714 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)+99 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)+58 System.Data.Entity.Core.Mapping.Update.Internal.d__0.MoveNext()+417
[UpdateException: An error occurred while updating the entries. See the inner exception for details.]
System.Data.Entity.Core.Mapping.Update.Internal.<UpdateAsync>d__0.MoveNext() +640
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Data.Entity.Core.Objects.<ExecuteInTransactionAsync>d__3d`1.MoveNext() +741
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Data.Entity.Core.Objects.<SaveChangesToStoreAsync>d__39.MoveNext() +379
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Data.Entity.SqlServer.<ExecuteAsyncImplementation>d__9`1.MoveNext() +346
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Data.Entity.Core.Objects.<SaveChangesInternalAsync>d__31.MoveNext() +799
[DbUpdateException: An error occurred while updating the entries. See the inner exception for details.]
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.AspNet.Identity.EntityFramework.<SaveChanges>d__61.MoveNext() +214
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.AspNet.Identity.EntityFramework.<CreateAsync>d__38.MoveNext() +243
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) +25
Microsoft.AspNet.Identity.<CreateAsync>d__73.MoveNext() +1050
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.AspNet.Identity.<CreateAsync>d__79.MoveNext() +442
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +28
hr_pcms.Controllers.<Register>d__15.MoveNext() in C:\Users\Administrator\source\repos\hr_pcms\hr_pcms\Controllers\AccountController.cs:155
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +97
System.Web.Mvc.Async.<>c__DisplayClass8_0.<BeginInvokeAsynchronousActionMethod>b__1(IAsyncResult asyncResult) +17
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__11_0() +50
System.Web.Mvc.Async.<>c__DisplayClass11_1.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass7_0.<BeginInvokeActionMethodWithFilters>b__1(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__3() +35
System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.InvokeEndHandler(IAsyncResult ar) +152
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +125
在我使用的此应用程序中,选择了“个人身份验证”。我从未编辑过AccountController,但是我通过向AspNetUsers表中添加列来扩展了模型。
任何有帮助的建议都会很棒。
答案 0 :(得分:0)
似乎您添加到AspNetUsers表中的列包含Department_Department_Id的外键。 我相信的问题是您要添加用户-但添加代码未设置该用户的Department_Id-因此,实际上它为Department_Id添加了null,并且键不能为null。要解决此问题,请创建一个从ApplicationUser派生的自定义MyUser类,包括Department_Id和其他任何相关列,并使用该派生类创建新用户。然后在调用Create之前分配DepartmentId。
我前一阵子做过,可能有必要将它添加到Google上,因为有一些示例如何将列添加到已定义的AspNet表中。我相信我也更新了该项目用来创建表的脚本,并在其中定义了新列,因此,如果在没有数据库的情况下运行,它将创建具有正确配置的新表。根据您的文字,您可能已经完成了此操作...
更新-(我只能在这里添加,需要更多代表才能添加或回复评论)。
知道你可以用Google-我做到了。
您没有评论是否只是将列添加到AspNetUsers模型中-还是创建了我提到的派生类。其他人回答了我做的同样的事情-您不能先实例化一个新用户而不先为其分配DepartmentId-并且因为您需要先存在UserId而不能首先执行它-因此它必须像我一样同时完成建议。
以下是一些将列正确添加到AspNetUser的链接:
看看这些链接,看看它有多容易。这是一个快速的想法-未在VS中完成,很抱歉-未测试。只是给你一个大概的想法... 我无法访问去年完成的项目,因此无法提供快速准确的答案。
public class ApplicationUser : IdentityUser
{
// Because it is derived, all existing AspNetUser columns are inherited
// just need to add your new columns
public int DepartmentId { get; set; }
}
// model used for login page - with validation within page for items
public class LoginViewModel()
{
public string username { get; set; }
public string password { get; set; }
public List<SelectListItem> DepartmentList {
get {return new List<SelectListItem>() {
new SelectListItem() {Text = "Department A", Value = "1"},
new SelectListItem() {Text = "Department B", Value = "2"},
new SelectListItem() {Text = "Department C", Value = "3"}
};
}
private int selectedDepartment {
return DepartmentList.SelectedValue != null ?
Convert.Int32(DepartmentList.SelectedValue) : -1;
}
}
在您的网页上(您未说过使用的是asp.net/mvc/other)-他们也必须选择要登录的部门,可能是一个带有
值的下拉菜单Html.DropDownFor(x => x.SelectedItem, Model.DepartmentList)
// then something like
public async Task<ActionResult> Login(LoginViewModel lmodel, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(lmodel);
}
ApplicationUser user = new ApplicationUser() {
UserName = lmodel.username,
Password = lmodel.password,
//... other AspNetUser values assigned?
//...,
Department_Id = lmodel.selectedDepartment
}
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded) {
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
}