身份 - 与RegisterViewModel的一对一关系

时间:2017-11-21 21:18:40

标签: asp.net .net asp.net-mvc entity-framework asp.net-identity

我是MVC的新手,并且一直用这个来拉我的头发。我已经大胆了,所以需要有人拯救剩下的东西!

我正在使用asp.net Identity并尝试在RegisterViewModel和StoreDetails之间创建一对一关系,真的希望有人可以帮助我!

这是我的RegisterViewModel

   public class RegisterViewModel
{

    public string FirstName { get; set; }
    public string LastName { get; set; }

    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    public virtual StoreDetails StoreDetails { get; set; }

}

这是我的StoreDetails模型:

public class StoreDetails
{
    [Key, ForeignKey("RegisterViewModel")]
    public string StoreName { get; set; }

    public virtual RegisterViewModel RegisterViewModel { get; set; }
}

控制器:

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser {

                // PERSONAL DETAILS
                UserName = model.Email,
                Email = model.Email,
                FirstName = model.FirstName,
                LastName = model.LastName
            };

            var storeDetails = new StoreDetails {
                // STORE DETAILS
                StoreName = model.StoreDetails.StoreName
            };


            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>");


                // UPDATE DB WITH STORE DETAILS DATA
                var db = new ApplicationDbContext();
                db.StoreDetails.Add(new StoreDetails
                {
                    StoreName = model.StoreDetails.StoreName
                });
                db.SaveChanges();

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

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

我想要实现的是在注册时,使用以下输入生成StoreDetails表:

@Html.TextBoxFor(m => m.StoreDetails.StoreName)

如果您需要任何进一步的细节,请询问。

由于

2 个答案:

答案 0 :(得分:1)

RegisterViewModel不是真实的实体,即被EF保存到数据库中的人。它只是一个载体对象,它将电子邮件和密码的值传递到称为ApplicationUser的真实用户/人对象中。这是一个视图模型,而不是真实的模型。

在您的示例中,您在正确的RegisterViewModel中添加了StoreDetails。但是您还需要将它作为属性添加到ApplicationUser类中。

public class ApplicationUser {

public virtual StoreDetails StoreDetails { get; set; }

然后运行您的迁移。

将任何内容添加到RegisterViewModel中都是为了从视图层传递数据,从而可以安全地保护进入数据库的对象。

即 这样做不会做任何事情,因为viewmodel不存在于数据库中

public class StoreDetails
{
    [Key, ForeignKey("RegisterViewModel")] //this will not work remove
    public string StoreName { get; set; }

    public virtual RegisterViewModel RegisterViewModel { get; set; }// remove
}

答案 1 :(得分:-1)

public Ienumerable<StoreDetails> StoreDetails { get; set; }

public int StoreDetailsId { get; set; }

在控制器中:

using (var db = ApplicationDbContext.Create())
{
    model.StoreDetails = db.StoreDetails.ToList();
}