MVC标识 - INSERT语句与FOREIGN KEY约束

时间:2016-03-28 18:58:46

标签: sql-server asp.net-mvc asp.net-identity

我知道这个问题已经讨论了几次,但这个问题与内置的身份模型有关。

我创建了一个名为" Company"的自定义模型。注册新用户时,我还要选择公司名称。

我已将所需数据添加到RegisterViewModel中,并且视图和表单按原样显示。我已在公司表中播种了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);

任何想法以及这里有什么问题?

2 个答案:

答案 0 :(得分:0)

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(因为整个实体不会通过网络传输,也不应出于安全目的(输入错误,黑客攻击等)。) / p>

你的ViewModel(在这种情况下RegisterViewModel应该只有CompanyID(它是Company实体的PK。)然后应该用它来填充新用户{{ 1}}(ApplicationUser)通过执行查找然后分配给user。例如

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. } 实体有两个属性(大多数属性),一个用于ID,一个用于外部关系; e.g。

ApplicationUser

您只需指定/或。在这种情况下,您不需要在填充public int CompanyID { get; set; } // ID property [ForeignKey("CompanyID")] public virtual Company Company { get; set; } // entity property 之前执行查找,只需设置ApplicationUser

答案 1 :(得分:0)

看来我发现错误归功于你的上一个建议!我试图设置外键的值,如果ID ...

对我有用的代码:

function GapiProxy() {
  this.haveGapi = initializeGapiClient();
  this.list = arg => haveGapi.then(g => g.client.youtube.search.list(arg));
  this.client = { youtube: { search: { list: this.list } } };
}

let gapi = new GapiProxy();
b.onclick = () => gapi.client.youtube.search.list(...);