[英]SqlException: Cannot insert explicit value for identity column in table 'AspNetUsers' when IDENTITY_INSERT is set to OFF
[英]How to insert a value in Database when using MVC identity framework in AspNetUsers Table?
我想在 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);
您通常不能简单地向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,
};
还要进行以下更改:
在Startup.cs
ConfigureServices
方法中
services.AddIdentity<ApplicationUser, IdentityRole>();
在 AccountController 中,
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
添加迁移以使此更改生效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.