实体框架ASP.NET MVC6在身份模型中,创建新记录而不是将其链接到现有记录

时间:2018-04-21 00:34:05

标签: c# asp.net entity-framework

有人发布了同样的问题here,我遵循了每一步,但仍然无效。我之前使用相同的功能制作了许多工作项目。

因此,当用户注册新帐户时,他会填写表单并从2个下拉列表中选择UserType和Region。

其他一切正常,表格发布时。在DB中创建Region和UserType的新记录,并与新ID链接。

这是我的IdentityModel:

 public class ApplicationUser : IdentityUser
{
    [Required]
    public string Name { get; set; }

    public UserType UserType { get; set; }
    public int UserTypeId { get; set; }

    public Region Region { get; set; }
    public int RegionId { get; set; }

    [Display(Name ="Summoner Name")]
    public string SummonerName { get; set; }

    public int AccountId { get; set; }

    public async Task<ClaimsIdentity> 
    GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    // etc.....

这是我在AccountController中的注册操作

public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var UserTypeInDb = _context.UserTypes.Single(u => u.Id == model.UserTypeId);
            var RegionInDb = _context.Regions.Single(u => u.Id == model.RegionId);


            var user = new ApplicationUser {
                UserName = model.Email,
                Email = model.Email,
                Name = model.Name,
                Region = RegionInDb,
                UserType = UserTypeInDb
            };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        var viewModel = new RegisterViewModel()
        {
            Regions = _context.Regions.ToList(),
            UserTypes = _context.UserTypes.ToList()
        };
        return View(viewModel);
    }

2个变量UserTypeInDb和RegionInDb包含具有正确ID的正确记录。

那究竟是什么问题?并谢谢

1 个答案:

答案 0 :(得分:1)

我修改了它而没有更改ApplicationUser Class

            var user = new ApplicationUser {
            UserName = model.Email,
            Email = model.Email,
            RegionId = RegionInDb.Id,      <------- 
            UserTypeId = UserTypeInDb.Id,  <------- the fix
            UserType = UserTypeInDb
        };