我打开VS2013,创建了一个标识为1的空MVC项目,我想扩展identity Role class,为AspNetRoles添加一个额外的字段,所以我将这个类添加到Models Folder:
public class ApplicationRole : IdentityRole
{
public ApplicationRole() : base() { }
public ApplicationRole(string name, string title)
: base(name)
{
this.Title = title;
}
public virtual string Title { get; set; }
}
然后在PowerShell>启用迁移>添加迁移mig1,它在下面的类中创建:
public partial class mig1 : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.AspNetRoles",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(nullable: false, maxLength: 256),
Title = c.String(),
Discriminator = c.String(nullable: false, maxLength: 128), // The rogue column
})
.PrimaryKey(t => t.Id)
.Index(t => t.Name, unique: true, name: "RoleNameIndex");
{
//Another tables
{
但正如你所看到的,迁移创建了一个额外的列(鉴别器(,我不知道那是什么。
这不是我想要的,所以我评论了它,为了在配置类中播种,我添加了以下代码:
protected override void Seed(another.Models.ApplicationDbContext context)
{
if (!context.Roles.Any(r => r.Name == "AppAdmin"))
{
var store = new RoleStore<ApplicationRole>(context);
var manager = new RoleManager<ApplicationRole>(store);
var role = new ApplicationRole { Name = "AppAdmin", Title = "Admin" };
// Create: Create a role.
manager.Create(role);
}
if (!context.Roles.Any(r => r.Name == "Customer"))
{
var store = new RoleStore<ApplicationRole>(context);
var manager = new RoleManager<ApplicationRole>(store);
var role = new ApplicationRole { Name = "Customer",Title="usualuser" };
// Create: Create a role.
manager.Create(role);
}
}
然后在PowerShell>更新数据库中,它抛出了一个异常:"执行命令定义时出错。有关详细信息,请参阅内部异常。--->System.Data.SqlClient.SqlException:列名'Discriminator'无效">
编辑:这是我的上下文
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("ShopDB", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
您的上下文没有指定您正在使用自定义角色类,因此Entity Framework会扫描项目以查找从基本IdentityRole
类继承的任何类,并假设您可能希望使用TPH(按层次结构的表(,在TPH中可以将IdentityRole
和ApplicationRole
对象存储在同一DbSet
中。为此,它添加了一个Discriminator
列来区分类型
要解决此问题,您的上下文应该从其他允许您指定类型的IdentityDbContext
继承。例如:
public class ApplicationDbContext :
IdentityDbContext<ApplicationUser, ApplicationRole, string,
IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
{
//Snip
}