EF Core 添加迁移生成带有 ColumnName1 的额外列

EF Core Add-Migration generating extra column with ColumnName1

当我生成迁移时,我有以下实体,它创建了两个名为 RestrictedCategoryId 和 RestrictedCategoryId1(FK) 的列。 FK只生成一列怎么解决?

注意:我需要每个实体中的 OrderId。

`C#

public class Order
{
    public Guid Id { get; set; }
    public DateTime OrderDate { get; set; }

    private List<Category> _categories;
    public List<Category> Categories => _categories;
}
public class Category
{
    public Guid Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }

    public Guid OrderId { get; set; }
    public Order Order { get; set; }

    private List<RestrictionCategory> _restrictedCategories;
    public List<RestrictionCategory> RestrictedCategories => _restrictedCategories;
}
public class RestrictionCategory
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public Guid OrderId { get; set; }
    public Order Order { get; set; }
    public Guid CategoryId { get; set; }
    public Category Category { get; set; }        
    public Guid RestrictedCategoryId { get; set; }
    public Category RestrictedCategory { get; set; }
}
public class OrderConfiguration : IEntityTypeConfiguration<Order>
{
    public void Configure(EntityTypeBuilder<Order> builder)
    {
        builder.HasKey(o => o.Id);
        builder.Property(o => o.Id).IsRequired();
    }
}
public class CategoryConfiguration : IEntityTypeConfiguration<Category>
{
    public void Configure(EntityTypeBuilder<Category> builder)
    {
        builder.HasKey(c => new { c.Id, c.OrderId });
        builder.Property(o => o.Id).IsRequired();
        builder.Property(o => o.OrderId).IsRequired();

        builder.HasMany(c => c.RestrictedCategories).WithOne(cr => cr.Category)
            .HasForeignKey(cr => new { cr.CategoryId, cr.OrderId 
}).OnDelete(DeleteBehavior.NoAction);
    }
}
public class RestrictionCategoryConfiguration : IEntityTypeConfiguration<RestrictionCategory>
{
    public void Configure(EntityTypeBuilder<RestrictionCategory> builder)
    {
        builder.HasKey(c => new { c.Id, c.OrderId });
        builder.Property(o => o.Id).IsRequired();
        builder.Property(o => o.OrderId).IsRequired();

        builder.HasIndex(cr => new { cr.RestrictedCategoryId, cr.OrderId });
    }
}

` 实体与实际实体相似。

实际上你得到了两个额外的列:

RestrictedCategoryId = table.Column<Guid>(nullable: false),
RestrictedCategoryId1 = table.Column<Guid>(nullable: true), // <--
RestrictedCategoryOrderId = table.Column<Guid>(nullable: true) // <--

显然 EF Core Foreign Key Conventions 不能很好地处理组合键,因此您必须显式配置关系 - 类似于您为其他关系所做的,只是因为您的模型没有相应的集合导航属性 您必须将 HasMany 与泛型类型参数一起使用并且没有参数,例如里面 CategoryConfiguration:

builder.HasMany<RestrictionCategory>()
    .WithOne(cr => cr.RestrictedCategory)
    .HasForeignKey(cr => new { cr.RestrictedCategoryId, cr.OrderId})
    .OnDelete(DeleteBehavior.NoAction);