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

huangapple go评论98阅读模式
英文:

__EFMigrationsHistory remains empty even though the database is created

问题

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: &quot;AspNetRoleClaims&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: &quot;AspNetUsers&quot;,
            columns: table =&gt; new
            {
                Id = table.Column&lt;string&gt;(nullable: false),
                UserName = table.Column&lt;string&gt;(maxLength: 256, nullable: true),
                NormalizedUserName = table.Column&lt;string&gt;(maxLength: 256, nullable: true),
                Email = table.Column&lt;string&gt;(maxLength: 256, nullable: true),
                NormalizedEmail = table.Column&lt;string&gt;(maxLength: 256, nullable: true),
                EmailConfirmed = table.Column&lt;bool&gt;(nullable: false),
                PasswordHash = table.Column&lt;string&gt;(nullable: true),
                SecurityStamp = table.Column&lt;string&gt;(nullable: true),
                ConcurrencyStamp = table.Column&lt;string&gt;(nullable: true),
                PhoneNumber = table.Column&lt;string&gt;(nullable: true),
                PhoneNumberConfirmed = table.Column&lt;bool&gt;(nullable: false),
                TwoFactorEnabled = table.Column&lt;bool&gt;(nullable: false),
                LockoutEnd = table.Column&lt;DateTimeOffset&gt;(nullable: true),
                LockoutEnabled = table.Column&lt;bool&gt;(nullable: false),
                AccessFailedCount = table.Column&lt;int&gt;(nullable: false)
            },
            constraints: table =&gt;
            {
                table.PrimaryKey(&quot;PK_AspNetUsers&quot;, x =&gt; x.Id);
            });

        migrationBuilder.CreateTable(
            name: &quot;AspNetRoleClaims&quot;,
            columns: table =&gt; new
            {
                Id = table.Column&lt;int&gt;(nullable: false)
                    .Annotation(&quot;SqlServer:ValueGenerationStrategy&quot;, SqlServerValueGenerationStrategy.IdentityColumn),
                RoleId = table.Column&lt;string&gt;(nullable: false),
                ClaimType = table.Column&lt;string&gt;(nullable: true),
                ClaimValue = table.Column&lt;string&gt;(nullable: true)
            },
            constraints: table =&gt;
            {
                table.PrimaryKey(&quot;PK_AspNetRoleClaims&quot;, x =&gt; x.Id);
                table.ForeignKey(
                    name: &quot;FK_AspNetRoleClaims_AspNetRoles_RoleId&quot;,
                    column: x =&gt; x.RoleId,
                    principalTable: &quot;AspNetRoles&quot;,
                    principalColumn: &quot;Id&quot;,
                    onDelete: ReferentialAction.Cascade);
            });

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        migrationBuilder.DropTable(
            name: &quot;AspNetUsers&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(&quot;DefaultConnection&quot;) ?? throw new InvalidOperationException(&quot;Connection string &#39;DefaultConnection&#39; not found.&quot;);
        builder.Services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;
            options.UseSqlServer(connectionString));
        builder.Services.AddDatabaseDeveloperPageExceptionFilter();

        builder.Services.AddDefaultIdentity&lt;ApplicationUser&gt;(options =&gt; options.SignIn.RequireConfirmedAccount = true)
            .AddRoles&lt;IdentityRole&gt;()
            .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;();

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

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

        //identity password
        builder.Services.Configure&lt;IdentityOptions&gt;(options =&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(&quot;/Home/Error&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: &quot;default&quot;,
            pattern: &quot;{controller=Home}/{action=Index}/{id?}&quot;);
        app.MapRazorPages();

        using (var scope = app.Services.CreateScope())
        {
            var roleManager = scope.ServiceProvider.GetRequiredService&lt;RoleManager&lt;IdentityRole&gt;&gt;();
            var roles = new[] { &quot;SuperAdmin&quot;, &quot;Admin&quot;, &quot;Member&quot;, &quot;Guest&quot; };
            foreach (var role in roles)
            {
                if (!await roleManager.RoleExistsAsync(role))
                    await roleManager.CreateAsync(new IdentityRole(role));
            }
            var dbContext = scope.ServiceProvider.GetService&lt;ApplicationDbContext&gt;();
            var apps = new[] { &quot;AppName&quot; };
            if (dbContext is not null)
            {
                foreach (var application in apps)
                {
                    if (!dbContext.Applications!.Where(a =&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&lt;ApplicationUser&gt;().HasQueryFilter(user =&gt; user.IsEnabled);
        base.OnModelCreating(modelBuilder);
    }

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

答案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());
}

huangapple
  • 本文由 发表于 2023年8月10日 21:01:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76875974.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定