是否可以将Asp.net Identity与自动增量关键字段一起使用?

时间:2015-01-24 18:01:43

标签: c# asp.net entity-framework asp.net-identity

我使用long作为Id字段使用我自己的EF数据库。我创建了所有实体和相关的自定义商店。

但是,在注册新用户时,它会在调用SetPasswordHashAsync之前尝试调用CreateAsync,这意味着它正在尝试写入尚不存在的数据库记录当然这是一个错误。

看起来系统希望在将Id字段写入数据库之前就知道它,但在此之前它无法知道Id,因为它被设置为自动增量字段。

我错过了什么?这甚至可能吗?

以下是AccountController的代码(取自MVC项目模板)

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new User { UserName = model.Email, Email = model.Email };
            var result = await userManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                // We do not want the user to be logged in as soon as they register. We want them have to go through the login process.
                //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                // 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 View("DisplayEmail");
            }
            AddErrors(result);
        }

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

这是来自UserManager(来自Identity.core)的代码,名为

    public virtual async Task<IdentityResult> CreateAsync(TUser user, string password)
    {
        ThrowIfDisposed();
        var passwordStore = GetPasswordStore();
        if (user == null)
        {
            throw new ArgumentNullException("user");
        }
        if (password == null)
        {
            throw new ArgumentNullException("password");
        }
        var result = await UpdatePasswordInternal(passwordStore, user, password).WithCurrentCulture();
        if (!result.Succeeded)
        {
            return result;
        }
        return await CreateAsync(user).WithCurrentCulture();
    }

因此,您可以看到在调用createUser之前更新密码是预期的过程,但这是如何工作的?这对我来说似乎不对。

0 个答案:

没有答案