如何添加新属性和扩展ApplicationUser类
本文关键字:扩展 ApplicationUser 属性 新属性 何添加 添加 | 更新日期: 2023-09-27 18:05:44
这是一个带有身份的MVC5 Web应用程序。我试图在我的注册视图中添加一个下拉列表,所以当一个人注册自己时,他们可以选择自己的角色。我的注册视图模型目前只有一个成功的部门和仓库的下拉列表,但是当我试图为角色复制它时,它不起作用。
注意:我设想我所有的角色都在我的dbo中。AspNetRoles表和分配给这些角色的所有用户将在我的dbo中。AspNetUserRoles表。
我知道我需要做以下事情来工作,但我不确定我是否错过了什么:
- 创建一个类的ID和名称(在我的IdentityModels.cs)
- 创建一个ViewModel (RegisterViewMode)
添加一个(RoleList)来显示下拉列表中的对象
- 修改模型
- 在视图中编写CSHTML代码(我已经完成了)
(ConfigureRegisterViewModel方法)在帐户控制器POST方法中容纳角色id
这是我在这一行的AccountController中得到的错误
IEnumerable<RegisterViewModel> roles = db.Roles.OrderBy(u => u.Name);
不能隐式转换类型"System.Linq.IOrderedQueryable"来"System.Collections.Generic.IEnumerable"。存在显式转换(您是否缺少强制类型转换?)
可以有人谁是MVC专家指向我正确的方向,如何做到这一点?在未来,我将修改我的ApplicationUser类和这个RegisterViewModel来添加更多的变量,例如:年龄,街道地址和工作职位等
这是我的RegisterViewModel
的一个片段public class RegisterViewModel
{
//RoleID
public int Id { get; set; }
[Required(AllowEmptyStrings = false)]
//RoleName
[Display(Name = "RoleName")]
public string Name { get; set; }
public IEnumerable<SelectListItem> RolesList { get; set; }
//Department and Depot
public int DepotID { get; set; }
public IEnumerable<SelectListItem> DepotList { get; set; }
public IEnumerable<SelectListItem> DepartmentList { get; set; }
public int DepartmentID { get; set; }
}
这是我的POST和GET方法注册AccountController.cs
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
RegisterViewModel model = new RegisterViewModel();
ConfigureRegisterViewModel(model);
return View(model);
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (!ModelState.IsValid)
{
ConfigureRegisterViewModel(model);
return View(model);
}
var user = new ApplicationUser() {
UserName = model.Email,
Email = model.Email,
FirstMidName = model.FirstMidName,
LastName = model.LastName,
EnrollmentDate = model.EnrollmentDate,
DepotID = model.DepotID,
DepartmentID = model.DepartmentID,
Id = model.Id //My RoleID
};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking this link: <a href='"" + callbackUrl + "'">link</a>");
ViewBag.Link = callbackUrl;
return View("DisplayEmail");
}
AddErrors(result);
// If we got this far, something failed, redisplay form
ConfigureRegisterViewModel(model);
return View(model);
}
private void ConfigureRegisterViewModel(RegisterViewModel model)
{
IEnumerable<Department> departments = db.Departments.OrderBy(u => u.DepartmentName);
model.DepartmentList = departments.Select(a => new SelectListItem
{
Value = a.DepartmentID.ToString(),
Text = a.DepartmentName.ToString()
});
IEnumerable<Depot> depots = db.Depots.OrderBy(u => u.DepotName);
model.DepotList = depots.Select(a => new SelectListItem
{
Value = a.DepotID.ToString(),
Text = a.DepotName.ToString()
});
IEnumerable<RegisterViewModel> roles = db.Roles.OrderBy(u => u.Name); <-- ERROR HERE
model.RolesList = roles.Select(a => new SelectListItem
{
Value = a.Id.ToString(),
Text = a.Name.ToString()
});
}
Register.cshtml
<div class="form-group">
@Html.LabelFor(m => m.Id, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.Id, Model.RolesList, "Please select", new { @class = "form-control" })
</div>
</div>
此代码仅供参考
IdentityModel.cs (ApplicationUser类)
namespace RecreationalServicesTicketingSystem.Models
{
public class ApplicationUserLogin : IdentityUserLogin<int> { }
public class ApplicationUserClaim : IdentityUserClaim<int> { }
public class ApplicationUserRole : IdentityUserRole<int> { }
public class ApplicationRole : IdentityRole<int, ApplicationUserRole>, IRole<int>
{
public string Description { get; set; }
public ApplicationRole() : base() { }
public ApplicationRole(string name)
: this()
{
this.Name = name;
}
public ApplicationRole(string name, string description)
: this(name)
{
this.Description = description;
}
}
public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
public async Task<ClaimsIdentity>
GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
{
var userIdentity = await manager
.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
public bool IsAdministrator { get; set; }
[StringLength(50, MinimumLength = 1)]
public string LastName { get; set; }
[StringLength(50, MinimumLength = 1, ErrorMessage = "First name cannot be longer than 50 characters.")]
[Column("FirstName")]
public string FirstMidName { get; set; }
public string FullName
{
get { return FirstMidName + " " + LastName; }
}
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EnrollmentDate { get; set; }
public int DepartmentID { get; set; }
[ForeignKey("DepartmentID")]
public virtual Department Department { get; set; }
public int DepotID { get; set; }
[ForeignKey("DepotID")]
public virtual Depot Depot { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
//Adding Roles to Register page code start
//RoleID
public int Id { get; set; }
[Required(AllowEmptyStrings = false)]
//RoleName
[Display(Name = "RoleName")]
public string Name { get; set; }
//Adding Roles to Register page code end
}
public class ApplicationDbContext
: IdentityDbContext<ApplicationUser, ApplicationRole, int,
ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
static ApplicationDbContext()
{
Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public DbSet<Ticket> Tickets { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Depot> Depots { get; set; }
}
public class ApplicationUserStore :
UserStore<ApplicationUser, ApplicationRole, int,
ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUserStore<ApplicationUser, int>, IDisposable
{
public ApplicationUserStore()
: this(new IdentityDbContext())
{
base.DisposeContext = true;
}
public ApplicationUserStore(DbContext context)
: base(context)
{
}
}
public class ApplicationRoleStore
: RoleStore<ApplicationRole, int, ApplicationUserRole>,
IQueryableRoleStore<ApplicationRole, int>,
IRoleStore<ApplicationRole, int>, IDisposable
{
public ApplicationRoleStore()
: base(new IdentityDbContext())
{
base.DisposeContext = true;
}
public ApplicationRoleStore(DbContext context)
: base(context)
{
}
}
}
您缺少ToList()
功能。ToList
会帮你把它变成IEnumerable
。应该是
IEnumerable<RegisterViewModel> roles = db.Roles.OrderBy(u => u.Name).ToList();
解决方案是
IEnumerable