C# 在AspNetUsers表中使用MVC identity framework时,如何在数据库中插入值?
我想在DB中插入一个值,我正在使用Asp.Net Identity framework,在我的Register方法中,当新用户注册时,我还想添加一个新Id,默认情况下,该Id不是由Identity framework插入的C# 在AspNetUsers表中使用MVC identity framework时,如何在数据库中插入值?,c#,asp.net-mvc,asp.net-identity,C#,Asp.net Mvc,Asp.net Identity,我想在DB中插入一个值,我正在使用Asp.Net Identity framework,在我的Register方法中,当新用户注册时,我还想添加一个新Id,默认情况下,该Id不是由Identity framework插入的 if (User.IsInRole("Avanceon")) { var MaxCustomerId = db.AspNetUsers.Max(x => x.Customer_Id); if (ModelState.IsValid) {
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方法中
在AccountController中
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
添加迁移以使此更改生效您通常不能简单地将任何数据插入到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方法中
在AccountController中
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
添加迁移以使此更改生效您好,我尝试了您的解决方案,但仍然没有插入值???\n您还需要为此创建迁移。那么它应该可以工作。我尝试了你的解决方案,但仍然没有插入值???\n你也需要为此创建迁移。然后它应该会起作用在Channel9上有一个关于定制ASP.NET身份验证的好系列。我想这一集就是你想要的。它与下面的答案非常相似,但包括实体框架端所需的更改。在Channel9上有一个关于定制ASP.NET身份验证的好系列。我想这一集就是你想要的。它与下面的答案非常相似,但包括实体框架端所需的更改。