我想在数据库中插入一个值,并且我正在使用 Asp.Net 身份框架,当新用户注册时,在我的注册方法中,我还想添加一个默认client_id的新 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);
通常不能简单地将任何数据插入到表中AspNetUsers
。您需要创建一个类并从IdentityUser
继承它,并在类中进行必要的更改。
首先使用代码,您应该创建一个继承IdentityUser
的类ApplicationUser
。并在此处添加属性:
public class ApplicationUser : IdentityUser
{
[Required]
public string ClientID { get; set; }
}
然后在代码中定位ApplicationUser
(而不是IdentityUser
var user = new ApplicationUser
{
UserName = model.UserName,
Email = model.Email,
ClientID = model.ClientID,
};
同时进行以下更改:
ConfigureServices
Startup.cs
方法
services.AddIdentity<ApplicationUser, IdentityRole>();
在帐户控制器中,
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
添加迁移以使此更改生效