我知道这个问题已经讨论过几次了,但这个问题与内置的Identity模型有关。
我创建了一个名为"公司"的自定义模型。注册新用户时,我还想选择公司名称。
我已经将所需的数据添加到RegisterViewModel中,视图和表单将按原样显示。我已经在Company表中为2个公司设定了种子,因此该值不应为空。
public class RegisterViewModel
{
... Removed some irrelevant code ...
[Required(ErrorMessage = "You must select a company name.")]
[Display(Name = "Company")]
public int CompanyID { get; set; }
public virtual Company ApplicationUser_Company { get; set; }
当我想插入一个带有以下错误的新用户时,问题就出现了:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.AspNetUsers_dbo.Companies_CompanyID". The conflict occurred in database "aspnet-ProjectMed-20160327120257", table "dbo.Companies", column 'CompanyID'.
The statement has been terminated.
检查帐户控制器我看不到任何问题:
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
ViewBag.CompanyID = new SelectList(db.Companies, "CompanyID", "Company_Name");
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email, ApplicationUser_FirstName = model.ApplicationUser_FirstName, ApplicationUser_LastName = model.ApplicationUser_LastName, ApplicationUser_Company = model.ApplicationUser_Company };
var result = await UserManager.CreateAsync(user, model.Password); <<<---- This is where the error occurs <<<---
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
我也在复制SQL表:
AspNetUsers表:
CREATE TABLE [dbo].[AspNetUsers] (
[Id] NVARCHAR (128) NOT NULL,
[ApplicationUser_FirstName] NVARCHAR (50) NOT NULL,
[ApplicationUser_LastName] NVARCHAR (50) NOT NULL,
[CompanyID] INT NOT NULL,
[Email] NVARCHAR (256) NULL,
[EmailConfirmed] BIT NOT NULL,
[PasswordHash] NVARCHAR (MAX) NULL,
[SecurityStamp] NVARCHAR (MAX) NULL,
[PhoneNumber] NVARCHAR (MAX) NULL,
[PhoneNumberConfirmed] BIT NOT NULL,
[TwoFactorEnabled] BIT NOT NULL,
[LockoutEndDateUtc] DATETIME NULL,
[LockoutEnabled] BIT NOT NULL,
[AccessFailedCount] INT NOT NULL,
[UserName] NVARCHAR (256) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_dbo.AspNetUsers_dbo.Companies_CompanyID] FOREIGN KEY ([CompanyID]) REFERENCES [dbo].[Companies] ([CompanyID]) ON DELETE CASCADE
);
GO
CREATE NONCLUSTERED INDEX [IX_CompanyID]
ON [dbo].[AspNetUsers]([CompanyID] ASC);
GO
CREATE UNIQUE NONCLUSTERED INDEX [UserNameIndex]
ON [dbo].[AspNetUsers]([UserName] ASC);
公司表:
CREATE TABLE [dbo].[Companies] (
[CompanyID] INT IDENTITY (1, 1) NOT NULL,
[Company_Name] NVARCHAR (50) NOT NULL,
[Company_Code] NVARCHAR (9) NOT NULL,
[Company_Address1] NVARCHAR (100) NOT NULL,
[Company_Address2] NVARCHAR (100) NULL,
[Company_PostalCode] NVARCHAR (15) NOT NULL,
[Company_City] NVARCHAR (50) NOT NULL,
[CountryID] INT NOT NULL,
[Company_CLOG] BIT NOT NULL,
[Company_SubAgent] BIT NOT NULL,
CONSTRAINT [PK_dbo.Companies] PRIMARY KEY CLUSTERED ([CompanyID] ASC),
CONSTRAINT [FK_dbo.Companies_dbo.Countries_CountryID] FOREIGN KEY ([CountryID]) REFERENCES [dbo].[Countries] ([CountryID]) ON DELETE CASCADE
);
GO
CREATE UNIQUE NONCLUSTERED INDEX [IX_Company_Code]
ON [dbo].[Companies]([Company_Code] ASC);
GO
CREATE NONCLUSTERED INDEX [IX_CountryID]
ON [dbo].[Companies]([CountryID] ASC);
有什么想法吗?这里出了什么问题?
Gut告诉我它在这行以内(为了清晰/评论而分开):
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
ApplicationUser_FirstName = model.ApplicationUser_FirstName,
ApplicationUser_LastName = model.ApplicationUser_LastName,
ApplicationUser_Company = model.ApplicationUser_Company // <--
};
基本上,当在表单操作之间传递实体引用时,您希望引用ID(因为整个实体不会跨线传输,也不应该出于安全目的(格式错误的输入、黑客攻击等))
您的ViewModel(在本例中,RegisterViewModel
实际上应该只有CompanyID
(它是Company
实体的PK)。然后应该使用它通过执行查找然后分配给user
来填充新用户ApplicationUser
(user
)。例如
[HttpPost]
public async Task<ActionResult> Register(RegisterViewModel model)
{
// verify the models' valid
if (ModelState.IsValid)
{
// Perform a lookup to retrieve the selected company
var company = db.COmpanies.SingleOrDefault(x => x.CompanyID == model.CompanyID);
if (company != null) // Found it
{
// No go on to establish an application user
var user = new ApplicationUser {
/* ... */,
ApplicationUser_Company = company // entity we retrieved
};
//
// SignInManager yatta yata
//
}
}
return View(model); // Uh-oh fallback.
}
不过请注意,如果您的ApplicationUser
实体有两个属性(大多数都有),一个用于ID,另一个用于外部关系;例如
public int CompanyID { get; set; } // ID property
[ForeignKey("CompanyID")]
public virtual Company Company { get; set; } // entity property
您只需要指定其中一个/或。在这种情况下,在填充ApplicationUser
之前不需要执行查找,只需设置user.CompanyID = model.CompanyID;
由于你上次的建议,我似乎发现了错误!如果ID…
对我有用的代码:
[HttpPost]
public async Task<ActionResult> Register(RegisterViewModel model)
{
// verify the models' valid
if (ModelState.IsValid)
{
var user = new ApplicationUser {
/* ... */,
CompanyID = model.CompanyID // entity we retrieved
};
//
// SignInManager yatta yata
//
}
return View(model); // Uh-oh fallback.
}