[英]How to insert a value in Database when using MVC identity framework in AspNetUsers Table?
I want to insert a value in DB and I am using the Asp.Net Identity framework, in my Register method when a new user registers I also want to add a new Id which is client_id by default this id is not inserted by the identity framework?我想在 DB 中插入一个值,并且我正在使用 Asp.Net Identity 框架,当新用户注册时,在我的 Register 方法中,我还想添加一个新的 Id,默认情况下该 ID 是 client_id,该 ID 未由身份框架插入?
if (User.IsInRole("Avanceon"))
{
var MaxCustomerId = db.AspNetUsers.Max(x => x.Customer_Id);
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// Assign Role to user Here
await this.UserManager.AddToRoleAsync(user.Id, model.RoleName);
// Ends Here
// await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
ViewBag.userCreated = user.UserName + " Created Successfully";
ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
MaxCustomerId = MaxCustomerId + 1;
// db.AspNetUsers.LastOrDefault().Customer_Id = MaxCustomerId;
db.SaveChanges();
return View();
//return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
}
ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
return View(model);
You normally can't simply insert any data to AspNetUsers
table.您通常不能简单地向
AspNetUsers
表插入任何数据。 You'll need create a class and inherit it from IdentityUser
and do the necessary changes in your class.您需要创建一个类并从
IdentityUser
继承它,并在您的类中进行必要的更改。
With code first you should create a class say ApplicationUser
which inherits IdentityUser
.首先使用代码,您应该创建一个继承
IdentityUser
的类ApplicationUser
。 And add the property there:并在那里添加属性:
public class ApplicationUser : IdentityUser
{
[Required]
public string ClientID { get; set; }
}
And then target ApplicationUser
(instead of IdentityUser
) in your code:然后在您的代码中定位
ApplicationUser
(而不是IdentityUser
):
var user = new ApplicationUser
{
UserName = model.UserName,
Email = model.Email,
ClientID = model.ClientID,
};
Make below changes as well:还要进行以下更改:
In ConfigureServices
method of Startup.cs
在
Startup.cs
ConfigureServices
方法中
services.AddIdentity<ApplicationUser, IdentityRole>();
In AccountController,在 AccountController 中,
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
Add migration for this change to take effect添加迁移以使此更改生效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.