简体   繁体   English

EF Core 添加迁移问题 - 如何修复不同步迁移?

[英]EF Core Add-Migration Issue - How to fix out of sync migration?

I have a.Net Core 2.2 MVC App running locally, with added scaffolded Identity as the authentication (I have all the ASPNetUsers/ASPNetRoles tables etc).我有一个在本地运行的 .Net Core 2.2 MVC 应用程序,并添加了脚手架身份作为身份验证(我有所有 ASPNetUsers/ASPNetRoles 表等)。 I am using a Postgres Database.我正在使用 Postgres 数据库。 I also have two 2 context class in my project, one is the IdentityDbContext which was added with the scaffolded Identity code and i have my DbContext which maps all my non Identity tables in my project.我的项目中还有两个 2 上下文 class,一个是使用脚手架身份代码添加的IdentityDbContext ,我的DbContext映射了我项目中的所有非身份表。

Here is my IdentityDbContext class:这是我的IdentityDbContext class:

public class PhotoUploaderFormContext : IdentityDbContext<ApplicationUser, IdentityRole, string>
{
    public PhotoUploaderFormContext(DbContextOptions<PhotoUploaderFormContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
    }
}

This simply maps my ApplicationUser.cs class (which is the user account for logging into my App).这只是映射了我的ApplicationUser.cs class(这是登录我的应用程序的用户帐户)。 Everything was working fine prior with regards to adding new properties to my ApplicationUser.cs class, Adding a Migration, Updating Database, and then these additional properties appear in my ASPNetUsers table.在将新属性添加到我的ApplicationUser.cs class、添加迁移、更新数据库之前,一切工作正常,然后这些附加属性出现在我的ASPNetUsers表中。

I have recently tried to add another property to my Application.cs class.我最近尝试向我的Application.cs class 添加另一个属性。 (It has been a long while since I have done, and there as been additional migrations added with my DbContext class in between). (我已经做了很长时间了,并且在我的DbContext class 之间添加了额外的迁移)。

The migration code looked correct:迁移代码看起来正确:

  public partial class templateSubmission : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<string>(
                name: "SubmitTemplateFormAccess",
                table: "AspNetUsers",
                nullable: true);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                name: "SubmitTemplateFormAccess",
                table: "AspNetUsers");
        }
    }

However, when I try to Update-Database , (using the IdentityDbContext ), I get the following error:但是,当我尝试Update-Database (使用IdentityDbContext )时,出现以下错误:

Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 2.2.6-servicing-10079 initialized 'PhotoUploaderFormContext' using provider 'Npgsql.EntityFrameworkCore.PostgreSQL' with options: None
Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (37ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace WHERE c.relname='__EFMigrationsHistory');
Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (83ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace WHERE c.relname='__EFMigrationsHistory');
Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (128ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT "MigrationId", "ProductVersion"
      FROM "__EFMigrationsHistory"
      ORDER BY "MigrationId";
Applying migration '20200217104808_CreateIdentitySchema'.
Microsoft.EntityFrameworkCore.Migrations[20402]
      Applying migration '20200217104808_CreateIdentitySchema'.
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
      Failed executing DbCommand (240ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE "AspNetRoles" (
          "Id" text NOT NULL,
          "Name" character varying(256) NULL,
          "NormalizedName" character varying(256) NULL,
          "ConcurrencyStamp" text NULL,
          CONSTRAINT "PK_AspNetRoles" PRIMARY KEY ("Id")
      );
Npgsql.PostgresException (0x80004005): 42P07: relation "AspNetRoles" already exists
   at Npgsql.NpgsqlConnector.<>c__DisplayClass161_0.<<ReadMessage>g__ReadMessageLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Npgsql.NpgsqlConnector.<>c__DisplayClass161_0.<<ReadMessage>g__ReadMessageLong|0>d.MoveNext() in C:\projects\npgsql\src\Npgsql\NpgsqlConnector.cs:line 1032
--- End of stack trace from previous location where exception was thrown ---
   at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming) in C:\projects\npgsql\src\Npgsql\NpgsqlDataReader.cs:line 490
   at Npgsql.NpgsqlDataReader.NextResult() in C:\projects\npgsql\src\Npgsql\NpgsqlDataReader.cs:line 332
   at Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken) in C:\projects\npgsql\src\Npgsql\NpgsqlCommand.cs:line 1218
   at Npgsql.NpgsqlCommand.ExecuteNonQuery(Boolean async, CancellationToken cancellationToken) in C:\projects\npgsql\src\Npgsql\NpgsqlCommand.cs:line 1042
   at Npgsql.NpgsqlCommand.ExecuteNonQuery() in C:\projects\npgsql\src\Npgsql\NpgsqlCommand.cs:line 1025
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
Failed executing DbCommand (240ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE "AspNetRoles" (
    "Id" text NOT NULL,
    "Name" character varying(256) NULL,
    "NormalizedName" character varying(256) NULL,
    "ConcurrencyStamp" text NULL,
    CONSTRAINT "PK_AspNetRoles" PRIMARY KEY ("Id")
);
Npgsql.PostgresException (0x80004005): 42P07: relation "AspNetRoles" already exists
   at Npgsql.NpgsqlConnector.<>c__DisplayClass161_0.<<ReadMessage>g__ReadMessageLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Npgsql.NpgsqlConnector.<>c__DisplayClass161_0.<<ReadMessage>g__ReadMessageLong|0>d.MoveNext() in C:\projects\npgsql\src\Npgsql\NpgsqlConnector.cs:line 1032
--- End of stack trace from previous location where exception was thrown ---
   at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming) in C:\projects\npgsql\src\Npgsql\NpgsqlDataReader.cs:line 490
   at Npgsql.NpgsqlDataReader.NextResult() in C:\projects\npgsql\src\Npgsql\NpgsqlDataReader.cs:line 332
   at Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken) in C:\projects\npgsql\src\Npgsql\NpgsqlCommand.cs:line 1218
   at Npgsql.NpgsqlCommand.ExecuteNonQuery(Boolean async, CancellationToken cancellationToken) in C:\projects\npgsql\src\Npgsql\NpgsqlCommand.cs:line 1042
   at Npgsql.NpgsqlCommand.ExecuteNonQuery() in C:\projects\npgsql\src\Npgsql\NpgsqlCommand.cs:line 1025
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_1.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
42P07: relation "AspNetRoles" already exists

It seems to be applying an older migration - 20200217104808_CreateIdentitySchema .它似乎正在应用较旧的迁移 - 20200217104808_CreateIdentitySchema This was the initial migration that created all of my Identity tables, such as ASPNetRoles, AspNetUserClaims, AspNetUserLogins etc.这是创建我所有身份表的初始迁移,例如ASPNetRoles, AspNetUserClaims, AspNetUserLogins等。

Any idea how to fix this mess?知道如何解决这个烂摊子吗? I have been trying for several days but unable to.我已经尝试了几天但无法。 Online suggestions where to delete all my migrations and start over, but I wanted to see if i could avoid that.在线建议在哪里删除我的所有迁移并重新开始,但我想看看我是否可以避免这种情况。 Many thanks非常感谢

If you have one stable migration version in migrationHistory table, then如果您在 migrationHistory 表中有一个稳定的迁移版本,那么

1: run update-database {MIGRATION_NAME_WITHOUT DATE}
2: run remove-migration
3: run add-migrarion (this will add migrations for any pending changes)
4: finally run "update-database"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM