Insert users Id into multiple tabels using MVC Identity

后端 未结 2 839
北恋
北恋 2020-12-12 06:29

I want to insert user id to multiple tables after registration success

public async Task Register(RegisterViewModel model , RoleViewModel         


        
2条回答
  •  忘掉有多难
    2020-12-12 06:43

    You have at least two options for this

    First. if you are using Code First, you can create Your Activity class together with the ApplicationUser class. see how here https://go.microsoft.com/fwlink/?LinkID=317594

    Second. You can retrieve the user id just the way you did it here

    result = await UserManager.AddToRolesAsync(user.Id, model.RoleName);
    var currentId = user.Id;
    

    Also your Activity insert has to come after the user has been created just as the code below

    public async Task Register(RegisterViewModel model, RoleViewModel role)
    {
       if (ModelState.IsValid)
       {
           ApplicationDbContext entities = new ApplicationDbContext();
           var user = new ApplicationUser {UserName = model.UserName};            
    
           var result = await UserManager.CreateAsync(user, model.Password);
           if (result.Succeeded )
           {
               Activity activity = new Activity
               {
                   RoleId = model.RoleName,
                   UserId = user.Id,
               };
               entities.activities.Add(activity);
               entities.SaveChanges();
               result = await UserManager.AddToRolesAsync(user.Id, model.RoleName);
    
               await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
    
               return RedirectToAction("Index", "Home");
           }
    
           AddErrors(result);
       }
    }
    

提交回复
热议问题