在我的asp.net MVC 5项目中,我无法弄清楚为什么我收到此错误:
Invalid column name 'Discriminator'.
Invalid column name 'Discriminator'.
Invalid column name 'Discriminator'.
Invalid column name 'Description'.
这是我的代码:
RoleManager<IdentityRole> _roleManager = new RoleManager<IdentityRole>(
new RoleStore<IdentityRole>(new ApplicationDbContext()));
UserManager<ApplicationUser> _userManager = new UserManager<ApplicationUser>(
new UserStore<ApplicationUser>(new ApplicationDbContext()));
public bool CreateRole(string name, string description = "")
{
var idResult = _roleManager.Create(new IdentityRole(name)).Succeeded;
return idResult;
}
当我尝试执行此方法时,出现无效列错误。可能是什么?
编辑:
ApplicationDbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
if (modelBuilder == null)
{
throw new ArgumentNullException("modelBuilder");
}
modelBuilder.Entity<IdentityUser>().ToTable("AspNetUsers");
EntityTypeConfiguration<ApplicationUser> table =
modelBuilder.Entity<ApplicationUser>().ToTable("AspNetUsers");
table.Property((ApplicationUser u) => u.UserName).IsRequired();
modelBuilder.Entity<ApplicationUser>().HasMany<IdentityUserRole>((ApplicationUser u) => u.Roles);
modelBuilder.Entity<IdentityUserRole>().HasKey((IdentityUserRole r) =>
new { UserId = r.UserId, RoleId = r.RoleId }).ToTable("AspNetUserRoles");
entityTypeConfiguration.HasRequired<IdentityUser>((IdentityUserLogin u) => u.User);
EntityTypeConfiguration<IdentityUserClaim> table1 =
modelBuilder.Entity<IdentityUserClaim>().ToTable("AspNetUserClaims");
table1.HasRequired<IdentityUser>((IdentityUserClaim u) => u.User);
// Add this, so that IdentityRole can share a table with ApplicationRole:
modelBuilder.Entity<IdentityRole>().ToTable("AspNetRoles");
// Change these from IdentityRole to ApplicationRole:
EntityTypeConfiguration<ApplicationRole> entityTypeConfiguration1 =
modelBuilder.Entity<ApplicationRole>().ToTable("AspNetRoles");
entityTypeConfiguration1.Property((ApplicationRole r) => r.Name).IsRequired();
}
}
最佳答案
修改角色时(例如,如下所示在IdentityModels.cs中向模型添加属性):
public class ApplicationRole:IdentityRole
{
public string Description { get; set; }
public string AreaUsed { get; set; }
}
在代码优先方法中,它将重新创建数据库,并将3列添加到aspNetRoles而不是2列(是的-我也很惊讶)。附加列名是“Discriminator”类型:nvarchar(128)不为null。
当您添加更多角色时,它将自动获得值“IdentityRole”。
我猜想当禁用自动迁移时,不会添加此列,结果您将收到此错误“无效的列名”。我在身份为2.0的MVC 5.1项目中遇到了相同的问题
关于asp.net - 尝试创建角色时,列名区分符无效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21992432/