ASP.NET MVC将用户添加到他的家庭'在usermanger创建/插入他之后

时间:2016-01-25 17:41:58

标签: asp.net asp.net-mvc database asp.net-identity

我正在为家长做一份登记表。因此,当有人注册用户并且制作了一个家庭时。 Usermanager将用户插入到DB中。在此之后我想建立一个新的家庭并将用户添加到这个家庭。问题是,使用下面的代码,他抱怨用户已经存在。

希望你们能帮助我。 :)

家庭班:

public class Familie
{
    public int familieId { get; set; }
    public virtual Adres adres { get; set; }
    public virtual ICollection<ApplicationUser> contactPersonen { get; set;}
    public virtual ICollection<ApplicationUser> kinderen { get; set; }
    public ApplicationUser gezinsHoofd { get; set; }
}

控制器代码:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Registreer_Ouder(ContactPersViewModelmodel)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser
            {
                UserName = model.email,
                Email = model.email,
                voorNaam = model.voorNaam,
                achterNaam = model.achterNaam,
                PhoneNumber = model.gsm,
                PasswordHash = model.password,
            };

            Adres adres = new Adres
            {
                gemeente = db.Gemeente.Find(model.gemeente),
                nummer = model.nummer,
                straat = model.straat
            };
            Familie familie = new Familie
            {
                adres = adres
            };

            var result = await UserManager.CreateAsync(user, model.password);

            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                var currentUser = UserManager.FindByName(user.UserName);
                var roleresult = UserManager.AddToRole(currentUser.Id, "GezinsHoofd");

                try { 
                    db.Familie.Add(familie);
                    db.Familie.Find(familie.familieId).gezinsHoofd = user;
                    db.SaveChanges(); // ERROR IS HERE
                }
                catch(DbEntityValidationException ex)
                {
                    // Just reading the exception for now.. 
                    throw;
                }
                // For more information on how to enable account confirmation and password reset please visit http://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, "Bevestig uw registratie", "Om te bevestigen klik <a href=\"" + callbackUrl + "\">hier</a>");

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

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

Execption:

Error

在浏览器中 Error2

1 个答案:

答案 0 :(得分:0)

使用ASP.NET身份有时候有点棘手......重点是您要添加UserManager.CreateAsync(user, model.password)的用户。此方法将用户添加到数据库,但目前在当前数据库上下文中没有对用户的引用。

如果将user分配给模型中的元素(db.Familie.Find(familie.familieId).gezinsHoofd = user),则EF会尝试将用户再次添加到数据库中。您需要做的是从数据库加载创建的用户并将用户添加到family元素:

// some code ignored for readability
try { 
    db.Familie.Add(familie);
    // load user explicitly from database to include in the context
    var dbUser = db.ApplicationUser.Find(currentUser.Id);
    db.Familie.Find(familie.familieId).gezinsHoofd = dbUser;
    db.SaveChanges(); // There should not be any error here :)
 }
 catch(DbEntityValidationException ex)
 {
     // Just reading the exception for now.. 
     throw;
 }