我尝试通过迁移添加新表,但收到用户已存在的错误。
我的操作顺序如下: dotnet ef 迁移删除 -> 通过 postgres 终端手动清除数据库 -> dotnet ef 迁移添加 InitialMigrations -> dotnet ef 数据库更新(错误!)
虽然数据库本身没有表,但之前也有错误,已经绝望了,我拆除数据库并创建一个新数据库,没有任何表,但是当我尝试更新数据库时,出现以下错误:
失败:Microsoft.EntityFrameworkCore.Database.Command[20102] 执行 DbCommand 失败(17ms)[Parameters=[],CommandType='Text',CommandTimeout='30']
CREATE TABLE users (
id integer GENERATED BY DEFAULT AS IDENTITY,
role text NULL,
username text NULL,
password_hash text NULL,
email text NULL,
encryption_key text NULL,
api_key text NULL,
CONSTRAINT "PK_users" PRIMARY KEY (id)
);
执行 DbCommand 失败(17 毫秒)[参数=[],CommandType='Text',CommandTimeout='30']
CREATE TABLE users (
id integer GENERATED BY DEFAULT AS IDENTITY,
role text NULL,
username text NULL,
password_hash text NULL,
email text NULL,
encryption_key text NULL,
api_key text NULL,
CONSTRAINT "PK_users" PRIMARY KEY (id)
);
Npgsql.PostgresException (0x80004005): 42P07: relation "users" already exists
at Npgsql.Internal.NpgsqlConnector.<ReadMessage>g__ReadMessageLong|234_0(NpgsqlConnector connector, Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage)
at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
at Npgsql.NpgsqlDataReader.NextResult()
at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteNonQuery(Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.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 connectionString, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String connectionString, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Exception data:
Severity: ERROR
SqlState: 42P07
MessageText: relation "users" already exists
File: heap.c
Line: 1148
Routine: heap_create_with_catalog
42P07: relation "users" already exists
虽然数据库是干净的并且不包含任何表
这是文件模型:
public class UserFileModel
{
public string? fileId { get; set; }
public string? file_path { get; set; }
public string? file_name { get; set; }
public string? status { get; set; }
public int? result_scan { get; set; }
public string error_message { get; set; }
public string enc_time { get; set; }
public string dec_time { get; set; }
public string upload_time { get; set; }
public string download_time { get; set; }
public int? id { get; set; } // Внешний ключ
[ForeignKey("id")]
public UserModel User { get; set; } // Навигационное свойство
}
这是用户模型
public class UserModel
{
public int? id { get; set; }
public string? role { get; set; }
public string? username { get; set; }
public string? password_hash { get; set; }
public string? email { get; set; }
public string? encryption_key { get; set; }
public string? api_key { get; set; }
}
这是上下文类
public class FileCryptDbContext : DbContext
{
public DbSet<UserModel> Users { get; set; }
public DbSet<UserFileModel> Files { get; set; }
public FileCryptDbContext(DbContextOptions<FileCryptDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserFileModel>()
.HasOne(f => f.User)
.WithMany()
.HasForeignKey(f => f.id);
}
}
这是迁移过程中创建的 ModelSnapShot。
[DbContext(typeof(FileCryptDbContext))]
partial class FileCryptDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("FileCryptWeb.Models.UserFileModel", b =>
{
b.Property<int?>("id")
.HasColumnType("integer");
b.Property<string>("dec_time")
.IsRequired()
.HasColumnType("text");
b.Property<string>("download_time")
.IsRequired()
.HasColumnType("text");
b.Property<string>("enc_time")
.IsRequired()
.HasColumnType("text");
b.Property<string>("error_message")
.IsRequired()
.HasColumnType("text");
b.Property<string>("fileId")
.HasColumnType("text");
b.Property<string>("file_name")
.HasColumnType("text");
b.Property<string>("file_path")
.HasColumnType("text");
b.Property<int?>("result_scan")
.HasColumnType("integer");
b.Property<string>("status")
.HasColumnType("text");
b.Property<string>("upload_time")
.IsRequired()
.HasColumnType("text");
b.HasKey("id");
b.ToTable("files");
});
modelBuilder.Entity("FileCryptWeb.Models.UserModel", b =>
{
b.Property<int?>("id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int?>("id"));
b.Property<string>("api_key")
.HasColumnType("text");
b.Property<string>("email")
.HasColumnType("text");
b.Property<string>("encryption_key")
.HasColumnType("text");
b.Property<string>("password_hash")
.HasColumnType("text");
b.Property<string>("role")
.HasColumnType("text");
b.Property<string>("username")
.HasColumnType("text");
b.HasKey("id");
b.ToTable("users");
});
modelBuilder.Entity("FileCryptWeb.Models.UserFileModel", b =>
{
b.HasOne("FileCryptWeb.Models.UserModel", "User")
.WithMany()
.HasForeignKey("id")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
#pragma warning restore 612, 618
}
}

一切都变得非常明显和简单。删除迁移后,我没有更新数据库。于是输入这个命令就解决了所有问题。