注册成功后,我想在多个表中插入用户ID
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插入到活动表中的用户ID中
答案 0 :(得分:0)
您实例化了ApplicationDbContext context
,但没有使用它。
然后,您使用entities
,但这是从哪里来的?
仅显示此处的控制器代码,我想您应该这样做:
context.activities.Add(activity);
context.SaveChanges();
最后,您传入了RoleViewModel role
,但您没有使用它。也许您可以删除它?
答案 1 :(得分:0)
您至少有两个选择
首先。 如果使用的是Code First,则可以将Activity类与ApplicationUser类一起创建。看看这里https://go.microsoft.com/fwlink/?LinkID=317594
第二。 您可以按照此处的操作来获取用户ID
result = await UserManager.AddToRolesAsync(user.Id, model.RoleName);
var currentId = user.Id;
此外,必须在创建用户之后插入“活动” 就像下面的代码
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);
}
}