c# - 带有 IdentityDbContext 和 hasData 播种的 EFcore 创建 IdentityRole

标签 c# .net-core entity-framework-core entity-framework-migrations

我有点眼花; 我正在使用 dotnet core (2.1) EF 进行迁移。当我仅根据上下文创建第一个迁移时,实际上一切看起来都不错。

所以我有这样的上下文:

public class DataContext : IdentityDbContext<User, IdentityRole<Guid>, Guid>
{

    public virtual DbSet<Country> Countries { get; set; }
    public virtual DbSet<CountryUser> CountryUsers { get; set; }
    //..more stuff

    public DataContext(DbContextOptions options) : base(options)
    { }
}

因此在创建迁移后它要添加:

migrationBuilder.CreateTable(
            name: "AspNetRoles",
            columns: table => new
            {
                Id = table.Column<Guid>(nullable: false),
                Name = table.Column<string>(maxLength: 256, nullable:
                //etc. etc. Removed rest of migrations.

我认为一切都很好。

然后我开始关注下面的文章; How to seed an Admin user in EF Core 2.1.0?

设置HasData后并播种数据库,创建一个新的迁移,它在想要删除 AspNetRoles 的地方创建了一个新的迁移表并创建为新表 IdentityRole 。 我刚刚删除了数据库并尝试再次执行此操作,现在它只想在播种时插入数据。但我不明白我改变了什么,甚至更好的是,为什么它想要删除并创建不同的表。

有人可以解释一下它什么时候想创建 AspNetRoles当它想要创建IdentityRoles时(以及与之配套的其他表格)。

只是为了确定一下;上下文总是从

延伸

: IdentityDbContext<User, IdentityRole<Guid>, Guid>

还有我的User :

public class User : IdentityUser<Guid>
{
    public virtual ICollection<CountryUser> CountryUsers { get; set; }
}

谢谢!!

最佳答案

据我了解,您正在遵循以下方法:

modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "Admin", NormalizedName = "Admin".ToUpper() });

这段代码有两个问题。

第一个是 modelBuilder.Entity<IdentityRole>() 的用法。这使得IdentityRole EF Core 将类视为实体,因此 IdentityRoles它尝试创建的表。这是因为IdentityRole类与您的模型使用的类不同 - IdentityRole<Guid> 。将其更改为 modelBuilder.Entity<IdentityRole<Guid>>() (以及 new 运算符),问题将得到解决。

第二个问题是HasData 需要指定 PK 值,如 Data Seeding 中所述。 EF Core 文档部分:

The primary key value needs to be specified even if it's usually generated by the database. It will be used to detect data changes between migrations.

因此,除了更改 HasData泛型类型参数,您需要预先生成 Guid 以用作新角色的 Id(有关类似问题的更多详细信息,请参阅 Entity Framework Core Auto Generated guid)并使用如下内容:

modelBuilder.Entity<IdentityRole<Guid>>().HasData(
    new IdentityRole<Guid>
    {
        Id = new Guid("pre generated value"),
        Name = "Admin",
        NormalizedName = "Admin".ToUpper()
    }
);

关于c# - 带有 IdentityDbContext 和 hasData 播种的 EFcore 创建 IdentityRole,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53497164/

相关文章:

c# - 在 SQL Server Compact 3.5 上使用 CTE

c# - 测试 ASP.NET Core IMemoryCache 的正确方法

c# - 如何使用 EF Core 聚合数百万行

c# - EF Core 过滤器枚举存储为带有 LIKE 运算符的字符串

.net-core - 如何为上下文禁用日志

c# - EF Core - 当我指定自己的外键时,会自动添加不需要的外键

C# Active Directory 调用非常慢

c# - 我需要在主子关系中进行 2 级继承和抽象

c# - 发布 AWS Lambda .Net Core

asp.net-core - 哪些版本的 Windows Server 与 .NET Core 运行时 RID 匹配