![](/img/trans.png)
[英]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.