Insert users Id into multiple tabels using MVC Identity

后端 未结 2 830
北恋
北恋 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<ActionResult> 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);
       }
    }
    
    0 讨论(0)
  • 2020-12-12 06:43

    You instantiate the ApplicationDbContext context but you don't use it. You then use entities but where does that come from? With only the controller code shown here, my guess is you should do:

    context.activities.Add(activity);
    context.SaveChanges();
    

    Finally, you pass in RoleViewModel role but you don't use it. Maybe you can remove that?

    0 讨论(0)
提交回复
热议问题