51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

__EFMigrationsHistory 仍然为空,即使数据库已创建。

英文:

__EFMigrationsHistory remains empty even though the database is created

问题 {#heading}

I have translated the provided text:

嗨,我在EF Core 6中遇到了一个问题,即迁移的历史表仍然为空,但是当我检查SQL Server时,数据库已成功创建并且所有表也都创建了。
我使用了Code-First方法,所以我运行Add-Migration <name>来生成迁移。
当我运行Update-Database时,一切都正常运行。
我所做的是将EF Core从6.0.16升级到6.0.21,然后在我的模型中添加了一个新的实体mytablename,所以我生成了它的迁移。然后我运行Update-Database,现在它给了我这个错误:
Microsoft.Data.SqlClient.SqlException (0x80131904): 数据库中已存在一个名为'AspNetRoles'的对象。错误编号:2714,状态:6,类:16
mytablename已创建,但__EFMigrationsHistory未更新。
我尝试了一些解决方案,比如删除数据库并从头开始重新创建,然后尝试删除数据库和所有迁移并重新生成它们,但仍然没有解决问题,仍然出现相同的错误。
谢谢您帮助我,我是EF Core和DotNet产品的新手。

我尝试了一些解决方案,比如删除数据库并从头开始重新创建,然后尝试删除数据库和所有迁移并重新生成它们,但仍然没有解决问题,仍然出现相同的错误。
谢谢您帮助我,我是EF Core和DotNet产品的新手。
以下是第一个迁移:

public partial class CreateIdentitySchema : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: &quot;AspNetRoles&quot;,
            columns: table =&gt; new
            {
                Id = table.Column&lt;string&gt;(nullable: false),
                Name = table.Column&lt;string&gt;(maxLength: 256, nullable: true),
                NormalizedName = table.Column&lt;string&gt;(maxLength: 256, nullable: true),
                ConcurrencyStamp = table.Column&lt;string&gt;(nullable: true)
            },
            constraints: table =&gt;
            {
                table.PrimaryKey(&quot;PK_AspNetRoles&quot;, x =&gt; x.Id);
            });
    // 其他表的创建也在此处
}

protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: &amp;quot;AspNetRoleClaims&amp;quot;);

// 其他表的删除也在此处

}

}

当我手动填充__EFMigrationsHistory并运行update-database时,一切正常,但当我删除数据库并重新运行update-database时,会出现相同的错误。
当我运行dotnet ef migrations list时:

> 00000000000000_CreateIdentitySchema (待处理)
>
> 20230807142821_CreateAppDb (待处理)
>
> 20230809091829_AppTable (待处理)
>
> 20230809100343_UserPersonalData (待处理)
>
> 20230810084347_db (待处理)
>

>
> 程序:
>

public static class Program
{
    public static async Task Main(string[] args)
    {
        // 程序配置在此处
    }
}

>
> DbContext
>

public class ApplicationDbContext : 
    IdentityDbContext&lt;ApplicationUser&gt;
{
    // DbContext配置在此处
}

请注意,代码中的&quot;应该是",我已经做了修正。 英文:

Hi I have an issue with EF Core 6 that is the history table of migrations remains empty but when I check the sql server the db is created successfully with all the tables are created also.
I use Code-first approach so I run Add-Migration &lt;name&gt; to generate migrations.
When I run Update-Database I was running perfectly fine.
what I did is updating EF Core from 6.0.16 to 6.0.21, Added new Entity mytablename to my models so I
generate its migration. then I run Update-Database it gives me now
Microsoft.Data.SqlClient.SqlException (0x80131904): There is already an object named &#39;AspNetRoles&#39; in the database. Error Number:2714,State:6,Class:16
mytablename is created but __EFMigrationsHistory is not updated.
I tried some solutions like drop db and recreated from scratch, then I tried deleting db and all migrations and regenerate them but it did not work still same error.
thank you for helping me I am new to EF Core and DotNet products.

I tried some solutions like dropping db and recreated it from scratch, then I tried deleting db and all migrations and regenerate them but it did not work still same error.
thank you for helping me I am new to EF Core and DotNet products.
here is the first migration:

public partial class CreateIdentitySchema : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: &quot;AspNetRoles&quot;,
            columns: table =&gt; new
            {
                Id = table.Column&lt;string&gt;(nullable: false),
                Name = table.Column&lt;string&gt;(maxLength: 256, nullable: true),
                NormalizedName = table.Column&lt;string&gt;(maxLength: 256, nullable: true),
                ConcurrencyStamp = table.Column&lt;string&gt;(nullable: true)
            },
            constraints: table =&gt;
            {
                table.PrimaryKey(&quot;PK_AspNetRoles&quot;, x =&gt; x.Id);
            });
    migrationBuilder.CreateTable(
        name: &amp;quot;AspNetUsers&amp;quot;,
        columns: table =&amp;gt; new
        {
            Id = table.Column&amp;lt;string&amp;gt;(nullable: false),
            UserName = table.Column&amp;lt;string&amp;gt;(maxLength: 256, nullable: true),
            NormalizedUserName = table.Column&amp;lt;string&amp;gt;(maxLength: 256, nullable: true),
            Email = table.Column&amp;lt;string&amp;gt;(maxLength: 256, nullable: true),
            NormalizedEmail = table.Column&amp;lt;string&amp;gt;(maxLength: 256, nullable: true),
            EmailConfirmed = table.Column&amp;lt;bool&amp;gt;(nullable: false),
            PasswordHash = table.Column&amp;lt;string&amp;gt;(nullable: true),
            SecurityStamp = table.Column&amp;lt;string&amp;gt;(nullable: true),
            ConcurrencyStamp = table.Column&amp;lt;string&amp;gt;(nullable: true),
            PhoneNumber = table.Column&amp;lt;string&amp;gt;(nullable: true),
            PhoneNumberConfirmed = table.Column&amp;lt;bool&amp;gt;(nullable: false),
            TwoFactorEnabled = table.Column&amp;lt;bool&amp;gt;(nullable: false),
            LockoutEnd = table.Column&amp;lt;DateTimeOffset&amp;gt;(nullable: true),
            LockoutEnabled = table.Column&amp;lt;bool&amp;gt;(nullable: false),
            AccessFailedCount = table.Column&amp;lt;int&amp;gt;(nullable: false)
        },
        constraints: table =&amp;gt;
        {
            table.PrimaryKey(&amp;quot;PK_AspNetUsers&amp;quot;, x =&amp;gt; x.Id);
        });
migrationBuilder.CreateTable(
    name: &amp;amp;quot;AspNetRoleClaims&amp;amp;quot;,
    columns: table =&amp;amp;gt; new
    {
        Id = table.Column&amp;amp;lt;int&amp;amp;gt;(nullable: false)
            .Annotation(&amp;amp;quot;SqlServer:ValueGenerationStrategy&amp;amp;quot;, SqlServerValueGenerationStrategy.IdentityColumn),
        RoleId = table.Column&amp;amp;lt;string&amp;amp;gt;(nullable: false),
        ClaimType = table.Column&amp;amp;lt;string&amp;amp;gt;(nullable: true),
        ClaimValue = table.Column&amp;amp;lt;string&amp;amp;gt;(nullable: true)
    },
    constraints: table =&amp;amp;gt;
    {
        table.PrimaryKey(&amp;amp;quot;PK_AspNetRoleClaims&amp;amp;quot;, x =&amp;amp;gt; x.Id);
        table.ForeignKey(
            name: &amp;amp;quot;FK_AspNetRoleClaims_AspNetRoles_RoleId&amp;amp;quot;,
            column: x =&amp;amp;gt; x.RoleId,
            principalTable: &amp;amp;quot;AspNetRoles&amp;amp;quot;,
            principalColumn: &amp;amp;quot;Id&amp;amp;quot;,
            onDelete: ReferentialAction.Cascade);
    });

migrationBuilder.CreateTable( name: &amp;amp;quot;AspNetUserClaims&amp;amp;quot;, columns: table =&amp;amp;gt; new { Id = table.Column&amp;amp;lt;int&amp;amp;gt;(nullable: false) .Annotation(&amp;amp;quot;SqlServer:ValueGenerationStrategy&amp;amp;quot;, SqlServerValueGenerationStrategy.IdentityColumn), UserId = table.Column&amp;amp;lt;string&amp;amp;gt;(nullable: false), ClaimType = table.Column&amp;amp;lt;string&amp;amp;gt;(nullable: true), ClaimValue = table.Column&amp;amp;lt;string&amp;amp;gt;(nullable: true) }, constraints: table =&amp;amp;gt; { table.PrimaryKey(&amp;amp;quot;PK_AspNetUserClaims&amp;amp;quot;, x =&amp;amp;gt; x.Id); table.ForeignKey( name: &amp;amp;quot;FK_AspNetUserClaims_AspNetUsers_UserId&amp;amp;quot;, column: x =&amp;amp;gt; x.UserId, principalTable: &amp;amp;quot;AspNetUsers&amp;amp;quot;, principalColumn: &amp;amp;quot;Id&amp;amp;quot;, onDelete: ReferentialAction.Cascade); });

migrationBuilder.CreateTable( name: &amp;amp;quot;AspNetUserLogins&amp;amp;quot;, columns: table =&amp;amp;gt; new { LoginProvider = table.Column&amp;amp;lt;string&amp;amp;gt;(maxLength: 128, nullable: false), ProviderKey = table.Column&amp;amp;lt;string&amp;amp;gt;(maxLength: 128, nullable: false), ProviderDisplayName = table.Column&amp;amp;lt;string&amp;amp;gt;(nullable: true), UserId = table.Column&amp;amp;lt;string&amp;amp;gt;(nullable: false) }, constraints: table =&amp;amp;gt; { table.PrimaryKey(&amp;amp;quot;PK_AspNetUserLogins&amp;amp;quot;, x =&amp;amp;gt; new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: &amp;amp;quot;FK_AspNetUserLogins_AspNetUsers_UserId&amp;amp;quot;, column: x =&amp;amp;gt; x.UserId, principalTable: &amp;amp;quot;AspNetUsers&amp;amp;quot;, principalColumn: &amp;amp;quot;Id&amp;amp;quot;, onDelete: ReferentialAction.Cascade); });

migrationBuilder.CreateTable( name: &amp;amp;quot;AspNetUserRoles&amp;amp;quot;, columns: table =&amp;amp;gt; new { UserId = table.Column&amp;amp;lt;string&amp;amp;gt;(nullable: false), RoleId = table.Column&amp;amp;lt;string&amp;amp;gt;(nullable: false) }, constraints: table =&amp;amp;gt; { table.PrimaryKey(&amp;amp;quot;PK_AspNetUserRoles&amp;amp;quot;, x =&amp;amp;gt; new { x.UserId, x.RoleId }); table.ForeignKey( name: &amp;amp;quot;FK_AspNetUserRoles_AspNetRoles_RoleId&amp;amp;quot;, column: x =&amp;amp;gt; x.RoleId, principalTable: &amp;amp;quot;AspNetRoles&amp;amp;quot;, principalColumn: &amp;amp;quot;Id&amp;amp;quot;, onDelete: ReferentialAction.Cascade); table.ForeignKey( name: &amp;amp;quot;FK_AspNetUserRoles_AspNetUsers_UserId&amp;amp;quot;, column: x =&amp;amp;gt; x.UserId, principalTable: &amp;amp;quot;AspNetUsers&amp;amp;quot;, principalColumn: &amp;amp;quot;Id&amp;amp;quot;, onDelete: ReferentialAction.Cascade); });

migrationBuilder.CreateTable( name: &amp;amp;quot;AspNetUserTokens&amp;amp;quot;, columns: table =&amp;amp;gt; new { UserId = table.Column&amp;amp;lt;string&amp;amp;gt;(nullable: false), LoginProvider = table.Column&amp;amp;lt;string&amp;amp;gt;(maxLength: 128, nullable: false), Name = table.Column&amp;amp;lt;string&amp;amp;gt;(maxLength: 128, nullable: false), Value = table.Column&amp;amp;lt;string&amp;amp;gt;(nullable: true) }, constraints: table =&amp;amp;gt; { table.PrimaryKey(&amp;amp;quot;PK_AspNetUserTokens&amp;amp;quot;, x =&amp;amp;gt; new { x.UserId, x.LoginProvider, x.Name }); table.ForeignKey( name: &amp;amp;quot;FK_AspNetUserTokens_AspNetUsers_UserId&amp;amp;quot;, column: x =&amp;amp;gt; x.UserId, principalTable: &amp;amp;quot;AspNetUsers&amp;amp;quot;, principalColumn: &amp;amp;quot;Id&amp;amp;quot;, onDelete: ReferentialAction.Cascade); });

migrationBuilder.CreateIndex( name: &amp;amp;quot;IX_AspNetRoleClaims_RoleId&amp;amp;quot;, table: &amp;amp;quot;AspNetRoleClaims&amp;amp;quot;, column: &amp;amp;quot;RoleId&amp;amp;quot;);

migrationBuilder.CreateIndex( name: &amp;amp;quot;RoleNameIndex&amp;amp;quot;, table: &amp;amp;quot;AspNetRoles&amp;amp;quot;, column: &amp;amp;quot;NormalizedName&amp;amp;quot;, unique: true, filter: &amp;amp;quot;[NormalizedName] IS NOT NULL&amp;amp;quot;);

migrationBuilder.CreateIndex( name: &amp;amp;quot;IX_AspNetUserClaims_UserId&amp;amp;quot;, table: &amp;amp;quot;AspNetUserClaims&amp;amp;quot;, column: &amp;amp;quot;UserId&amp;amp;quot;);

migrationBuilder.CreateIndex( name: &amp;amp;quot;IX_AspNetUserLogins_UserId&amp;amp;quot;, table: &amp;amp;quot;AspNetUserLogins&amp;amp;quot;, column: &amp;amp;quot;UserId&amp;amp;quot;);

migrationBuilder.CreateIndex( name: &amp;amp;quot;IX_AspNetUserRoles_RoleId&amp;amp;quot;, table: &amp;amp;quot;AspNetUserRoles&amp;amp;quot;, column: &amp;amp;quot;RoleId&amp;amp;quot;);

migrationBuilder.CreateIndex( name: &amp;amp;quot;EmailIndex&amp;amp;quot;, table: &amp;amp;quot;AspNetUsers&amp;amp;quot;, column: &amp;amp;quot;NormalizedEmail&amp;amp;quot;);

migrationBuilder.CreateIndex( name: &amp;amp;quot;UserNameIndex&amp;amp;quot;, table: &amp;amp;quot;AspNetUsers&amp;amp;quot;, column: &amp;amp;quot;NormalizedUserName&amp;amp;quot;, unique: true, filter: &amp;amp;quot;[NormalizedUserName] IS NOT NULL&amp;amp;quot;);

}

protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: &amp;quot;AspNetRoleClaims&amp;quot;);

migrationBuilder.DropTable(
    name: &amp;amp;quot;AspNetUserClaims&amp;amp;quot;);

migrationBuilder.DropTable( name: &amp;amp;quot;AspNetUserLogins&amp;amp;quot;);

migrationBuilder.DropTable( name: &amp;amp;quot;AspNetUserRoles&amp;amp;quot;);

migrationBuilder.DropTable( name: &amp;amp;quot;AspNetUserTokens&amp;amp;quot;);

migrationBuilder.DropTable( name: &amp;amp;quot;AspNetRoles&amp;amp;quot;);

migrationBuilder.DropTable( name: &amp;amp;quot;AspNetUsers&amp;amp;quot;);

}

}

When I populate __EFMigrationsHistory manually and run update-database it works fine , but when I drop the db and rerun update-database it gives the same error.
When I run dotnet ef migrations list:

> 00000000000000_CreateIdentitySchema (Pending)
>
> 20230807142821_CreateAppDb (Pending)
>
> 20230809091829_AppTable (Pending)
>
> 20230809100343_UserPersonalData (Pending)
>
> 20230810084347_db (Pending)
>

>
> Program:
>

    public static class Program
{
    public static async Task Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
    // Add services to the container.
    var connectionString = builder.Configuration.GetConnectionString(&amp;quot;DefaultConnection&amp;quot;) ?? throw new InvalidOperationException(&amp;quot;Connection string &amp;#39;DefaultConnection&amp;#39; not found.&amp;quot;);
    builder.Services.AddDbContext&amp;lt;ApplicationDbContext&amp;gt;(options =&amp;gt;
        options.UseSqlServer(connectionString));
    builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity&amp;amp;lt;ApplicationUser&amp;amp;gt;(options =&amp;amp;gt; options.SignIn.RequireConfirmedAccount = true)
    .AddRoles&amp;amp;lt;IdentityRole&amp;amp;gt;()
    .AddEntityFrameworkStores&amp;amp;lt;ApplicationDbContext&amp;amp;gt;();

builder.Services.AddControllersWithViews(); //authorization to apps policies builder.Services.AddAuthorization(options =&amp;amp;gt; { options.AddPolicy(&amp;amp;quot;DelibAppAccess&amp;amp;quot;, policy =&amp;amp;gt; policy.RequireClaim(&amp;amp;quot;AllowedToAppName&amp;amp;quot;)); });

builder.Services.AddScoped&amp;amp;lt;IApplicationService, ApplicationService&amp;amp;gt;(); builder.Services.AddScoped&amp;amp;lt;IRoleService, RoleService&amp;amp;gt;(); builder.Services.AddScoped&amp;amp;lt;IRegisterService, RegisterService&amp;amp;gt;();

//identity password builder.Services.Configure&amp;amp;lt;IdentityOptions&amp;amp;gt;(options =&amp;amp;gt; { // Default Password settings. options.Password.RequireDigit = false; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequiredLength = 6; options.Password.RequiredUniqueChars = 0; });

var app = builder.Build();

// Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseMigrationsEndPoint(); } else { app.UseExceptionHandler(&amp;amp;quot;/Home/Error&amp;amp;quot;); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); }

app.UseHttpsRedirection(); app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication(); app.UseAuthorization();

app.MapControllerRoute( name: &amp;amp;quot;default&amp;amp;quot;, pattern: &amp;amp;quot;{controller=Home}/{action=Index}/{id?}&amp;amp;quot;); app.MapRazorPages();

using (var scope = app.Services.CreateScope()) { var roleManager = scope.ServiceProvider.GetRequiredService&amp;amp;lt;RoleManager&amp;amp;lt;IdentityRole&amp;amp;gt;&amp;amp;gt;(); var roles = new[] { &amp;amp;quot;SuperAdmin&amp;amp;quot;, &amp;amp;quot;Admin&amp;amp;quot;, &amp;amp;quot;Member&amp;amp;quot;, &amp;amp;quot;Guest&amp;amp;quot; }; foreach (var role in roles) { if (!await roleManager.RoleExistsAsync(role)) await roleManager.CreateAsync(new IdentityRole(role)); } var dbContext = scope.ServiceProvider.GetService&amp;amp;lt;ApplicationDbContext&amp;amp;gt;(); var apps = new[] { &amp;amp;quot;AppName&amp;amp;quot; }; if (dbContext is not null) { foreach (var application in apps) { if (!dbContext.Applications!.Where(a =&amp;amp;gt; a.Label.Equals(application)).Any()) { dbContext.Applications!.Add(new Application() { Label = application }); } } await dbContext.SaveChangesAsync(); } } app.Run();

}

}

>
> DbContext
>

public class ApplicationDbContext : 
    IdentityDbContext&lt;ApplicationUser&gt;
    {
    public ApplicationDbContext()
    {
    }
    public ApplicationDbContext(DbContextOptions&lt;ApplicationDbContext&gt; options) : base(options)
    {
        try
            {
                if (Database.GetService&lt;IDatabaseCreator&gt;() is RelationalDatabaseCreator databaseCreator)
                {
                    if (!databaseCreator.CanConnect())
                    {
                        databaseCreator.CreateAsync().Wait();
                    }
                    if (!databaseCreator.HasTables())
                    {
                        databaseCreator.CreateTablesAsync().Wait();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    //filtering users by isEnabled
    modelBuilder.Entity&amp;lt;ApplicationUser&amp;gt;().HasQueryFilter(user =&amp;gt; user.IsEnabled);
    base.OnModelCreating(modelBuilder);
}

public DbSet&amp;lt;Application&amp;gt;? Applications { get; set; }

}

答案1 {#1}

得分: 0

我通过移除以下代码解决了这个问题:

try
{
  if (Database.GetService<IDatabaseCreator>() is RelationalDatabaseCreator databaseCreator)
  {
    if (!databaseCreator.CanConnect())
    {
      databaseCreator.CreateAsync().Wait();
    }
    if (!databaseCreator.HasTables())
    {
      databaseCreator.CreateTablesAsync().Wait();
    }
  }
}
catch (Exception ex)
{
  Console.WriteLine(ex.ToString());
}

英文:

I solved the problem by removing:

try
{
  if (Database.GetService&lt;IDatabaseCreator&gt;() is RelationalDatabaseCreator databaseCreator)
  {
    if (!databaseCreator.CanConnect())
    {
      databaseCreator.CreateAsync().Wait();
    }
    if (!databaseCreator.HasTables())
    {
      databaseCreator.CreateTablesAsync().Wait();
    }
  }
}
catch (Exception ex)
{
  Console.WriteLine(ex.ToString());
}

赞(1)
未经允许不得转载:工具盒子 » __EFMigrationsHistory 仍然为空,即使数据库已创建。