使用MVC身份将用户ID插入多个表格 [英] Insert users Id into multiple tabels using MVC Identity

查看:127
本文介绍了使用MVC身份将用户ID插入多个表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注册成功后,我想在多个表中插入用户ID

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

public async Task<ActionResult> Register(RegisterViewModel model , RoleViewModel role )
    {
        if (ModelState.IsValid)
        {
            ApplicationDbContext context = new ApplicationDbContext();
            var user = new ApplicationUser {
                UserName = model.UserName,};

            Activity activity = new Activity
            {
                RoleId = model.RoleName,
                UserId = model.Id,
            };
            entities.activities.Add(activity);
            entities.SaveChanges();

            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded )
            {
                result = await UserManager.AddToRolesAsync(user.Id, model.RoleName);

                await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

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

            AddErrors(result);
        }

这是AcountController,什么都没有发生,我想将用户表中的ID插入到活动表中的UserId中

This is AcountController , no thing happen I want to insert Id from users table to UserId in Activity Table

推荐答案

为此您至少有两个选择

首先. 如果使用的是Code First,则可以将Activity类与ApplicationUser类一起创建.在此处了解如何 https://go.microsoft.com/fwlink/?LinkID=317594

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

第二. 您可以按照此处的操作来获取用户ID

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

这篇关于使用MVC身份将用户ID插入多个表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆