Entity Framework 核心 - 使用 Npgsql 提供程序迁移失败

Entity Framework Core - Failed migration with Npgsql provider

尝试使用 Entity Framework Core 2.0.1 和提供程序 npgsql 2.0.1 从其模型创建数据库时出现错误。

错误描述为:

"constraint «FK_PiezasStockExterno_ContenedoresDocumentos_IdContenedorDocume» for relation «PiezasStockExterno» already exists".

我没有调用 Database.EnsureCreated(),因为我知道它会在迁移时造成问题,并且数据库之前已被删除,所以我确保它不存在。它发生在使用以下命令或调用 Database.EnsureCreated() 时。真正的问题可能是什么?

错误脚本:

CREATE TABLE "public"."PiezasStockExterno" 
(    
"Id" serial NOT NULL,   
"IdContenedorDocumentosPieza" int4 NULL,    
"IdContenedorDocumentosVehiculo" int4 NULL,

CONSTRAINT "PK_PiezasStockExterno" PRIMARY KEY ("Id"),    
CONSTRAINT "FK_PiezasStockExterno_ContenedoresDocumentos_IdContenedorDocumentosPieza" 
    FOREIGN KEY ("IdContenedorDocumentosPieza") 
    REFERENCES "public"."ContenedoresDocumentos" ("Id") ON DELETE RESTRICT,    
CONSTRAINT "FK_PiezasStockExterno_ContenedoresDocumentos_IdContenedorDocumentosVehiculo" 
    FOREIGN KEY ("IdContenedorDocumentosVehiculo") 
    REFERENCES "public"."ContenedoresDocumentos" ("Id") ON DELETE RESTRICT
)

型号:

[Table("PiezasStockExterno", Schema = "public")]
public class PiezaStockExterno
{

    [Key]
    public int Id { get; set; }

    public int? IdContenedorDocumentosPieza { get; set; }

    [ForeignKey("IdContenedorDocumentosPieza")]
    public virtual ContenedorDocumentos ContenedorDocumentosPieza { get; set; }

    public int? IdContenedorDocumentosVehiculo { get; set; }

    [ForeignKey("IdContenedorDocumentosVehiculo")]
    public virtual ContenedorDocumentos ContenedorDocumentosVehiculo { get; set; }

}

[Table("ContenedoresDocumentos", Schema = "public")]
public class ContenedorDocumentos
{

    [Key]
    public int Id { get; set; }

    [InverseProperty("ContenedorDocumentos")]
    public IList<Imagen> Imagenes { get; set; }

    [InverseProperty("ContenedorDocumentos")]
    public IList<Foto> Fotos { get; set; }

    [InverseProperty("ContenedorDocumentos")]
    public IList<Documento> Documentos { get; set; }

    [InverseProperty("ContenedorDocumentos")]
    public IList<Video> Videos { get; set; }

}

上下文:

public NContext(DbContextOptions<NContext> options) : base(options)
{

}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
    optionsBuilder.UseNpgsql(ConnectionString, b => b.MigrationsAssembly("WebAPI"));
    optionsBuilder.EnableSensitiveDataLogging();
    base.OnConfiguring(optionsBuilder);
}

Startup.cs 在 WebAPI 项目中:

public void ConfigureServices(IServiceCollection services)
{
    services.AddEntityFrameworkNpgsql().AddDbContext<Infrastructure.Data.NContext>();       

    services.AddMvc()
        .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()) 
        .AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

    AutoMapperConfig.Initialize();
}

命令:

dotnet ef migrations add InitialMigration
dotnet ef database update

OR

Database.EnsureCreated()

InitialMigration.cs:

    migrationBuilder.CreateTable(
            name: "PiezasStockExterno",
            schema: "public",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),                    
                IdContenedorDocumentosPieza = table.Column<int>(nullable: true),
                IdContenedorDocumentosVehiculo = table.Column<int>(nullable: true)                    
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_PiezasStockExterno", x => x.Id);
                table.ForeignKey(
                    name: "FK_PiezasStockExterno_ContenedoresDocumentos_IdContenedorDocumentosPieza",
                    column: x => x.IdContenedorDocumentosPieza,
                    principalSchema: "public",
                    principalTable: "ContenedoresDocumentos",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Restrict);
                table.ForeignKey(
                    name: "FK_PiezasStockExterno_ContenedoresDocumentos_IdContenedorDocumentosVehiculo",
                    column: x => x.IdContenedorDocumentosVehiculo,
                    principalSchema: "public",
                    principalTable: "ContenedoresDocumentos",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Restrict);
            });

你肯定是在用 FK 约束名称击中 PostgreSQL Max Identifier Length of 63 bytes,截断后变成相同的名称,因此令人困惑的 already exist 错误(尽管它可以可以看到名称被截断了)。

由于当前可以指定 FK 约束名称 only with Fluent API,您需要覆盖 OnModelCreating 并添加以下代码(使用您认为有意义的任何名称,不要超过 63 个字符) :

modelBuilder.Entity<PiezaStockExterno>()
    .HasOne(e => e.ContenedorDocumentosPieza)
    .WithMany()
    .HasConstraintName("FK_PiezasStockExterno_IdContenedorDocumentosPieza");

modelBuilder.Entity<PiezaStockExterno>()
    .HasOne(e => e.ContenedorDocumentosVehiculo)
    .WithMany()
    .HasConstraintName("FK_PiezasStockExterno_IdContenedorDocumentosVehiculo");

如果您添加了反向集合导航属性,请不要忘记更新相应的 WithMany 调用。