如何在 EF 6 中重命名自动生成的 n:m table?

How to rename an autogenerated n:m table in EF 6?

我使用 EF 6 设置了一个数据库。我使用下面的代码成功配置了多对多关系:

public class Software
{
    public string Id { get; set; }

    public string Version { get; set; }

    public string Name { get; set; }

    // Navigation property for machineSoftware
    public virtual ICollection<Machine> MachineSoftwares { get; set; }
}

public class Machine
{
    public int MachineId { get; set; }

    public string Model { get; set; }

    public string Customer { get; set; }

    public virtual ICollection<Software> MachineSoftwares { get; set; }
}

EF 6 自动创建了第三个 table MachineSoftwares。到目前为止一切顺利。

现在我想重命名 table,但我没有可以通过迁移重命名的 table 对应的 class。那么如何重命名 table MachineSoftwares?

隐式 many-to-many 结 table 的名称(及其列的名称)是通过 Map Fluent API.

配置的

但是为了访问 API,您必须首先使用 HasMany / WithMany 对映射关系:

modelBuilder.Entity<Software>()
    .HasMany(e => e.MachineSoftwares)
    .WithMany(e => e.MachineSoftwares)
    .Map(config => config
        .ToTable("the_desired_table_name")
        //.MapLeftKey("SoftwareId") // in case you need different column names
        //.MapRightKey("MachineId")
    );

您可以在代码中添加 Table 属性,EF 有更多属性选项,例如列名:

[Table("custom_name_table")]
public class Software
{
    public string Id { get; set; }

    [Column("the_version_name")]
    public string Version { get; set; }

    public string Name { get; set; }

    // Navigation property for machineSoftware
    public virtual ICollection<Machine> MachineSoftwares { get; set; }
}

检查这个 link https://www.entityframeworktutorial.net/code-first/table-dataannotations-attribute-in-code-first.aspx