.net core 2 - 唯一键约束违规

时间:2018-05-12 04:07:09

标签: c# .net entity-framework .net-core

我得到了

  

" SqlException:无法在标识列中插入显式值   表'组织'当IDENTITY_INSERT设置为OFF时。"

保存数据库中已存在的Organization时出现

错误。如果Organization是新的,它会毫无问题地进行 - OrganizationOrganization表中创建,并且在ASP NET Users中正确创建了对它的引用表

  [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            Organization currentOrg = new Organization();

            var existingOrg = _context.Organization.Where(m => m.OrganizationName == model.Organization);

            if (existingOrg.Count() > 0)
            {
                //currentOrg = _context.Organization.Find(existingOrg.First().Recno);
                currentOrg = existingOrg.First();
            }

            else
            {
                currentOrg.OrganizationName = model.Organization;
            }

            var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName
                , AddToConstantContact = model.AddToConstantContact,
                Organization = currentOrg, CityId = "1" };
            var result = await _userManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                _logger.LogInformation("User created a new account with password.");

                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                var callbackUrl = Url.EmailConfirmationLink(user.Id.ToString(), code, Request.Scheme);
                await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);

                await _signInManager.SignInAsync(user, isPersistent: false);
                _logger.LogInformation("User created a new account with password.");
                return RedirectToLocal(returnUrl);
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

1 个答案:

答案 0 :(得分:0)

不知道如何给予信任......但Sam的回答是正确的 - 以下代码解决了这个问题:

            if (existingOrg.Count() > 0)
            {
                //user.Organization = new Organization();
                user.OrganizationId = existingOrg.First().Recno;
            }

            else
            {
                user.Organization = new Organization();
                user.Organization.OrganizationName = model.Organization;
            }


public class ApplicationUser : IdentityUser
{
    public String FirstName { get; set; }

    public String LastName { get; set; }

    public String CityId { get; set; }

    [ForeignKey("OrganizationId")]
    public virtual Organization Organization { get; set; }

    public int? OrganizationId { get; set; }
}