如何更改 EF Core Fluent API 中的外键名称?

How to change foreign key name in EF Core Fluent API?

我正在尝试通过 EF Core fluent API 在两个 class 之间建立多对多关系。如何更改将为该关系创建的 table 之间的外键名称?

例如,如果我们在以下两个 class 之间创建 many-to-many 关系:

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Course> Courses { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string CourseName { get; set; }
    public string Description { get; set; }

    public virtual ICollection<Student> Students { get; set; }
}

// Fluent Api
public class UserMap : IEntityTypeConfiguration<User>
{
    public void Configure(EntityTypeBuilder<User> builder)
    {
        builder.HasKey(x => x.Id);
        builder.ToTable("Users");

        builder.HasMany<Course>(user => user.Courses)
               .WithMany(course => course.Users);
    }
}

一个table是这样创建的:

我想要的是使用我在 code-first 期间提供的外键名称创建 in-between table。

我知道我可以将 in-between table 写成 class 并用 one-to-many 关系更改名称,但我想用 code-first.

示例取自 EF 核心 documentation

您可能想为中间 table 添加一个新的 class:

public class StudentCourse
{
    public int FKStudentId { get; set; }
    public int FKCourseId { get; set; }

    public virtual Student Student { get; set; }
    public virtual Course Course { get; set; }

}

并替换导航属性:

public virtual ICollection<Course> Courses { get; set; }

public virtual ICollection<StudentCourse> Courses { get; set; }

Course class 中做同样的事情。

然后在流利的Api,你现在可以使用新的class。

public class StudentConfiguration : IEntityTypeConfiguration<Student>
{
    public void Configure(EntityTypeBuilder<Student> entity)
    {
        entity.HasKey(x => x.StudentId);

        entity.HasMany(student => student.Courses)
            .WithOne(course => course.Student)
            .HasForeignKey(x => x.FKStudentId);

    }
}

public class CourseConfiguration : IEntityTypeConfiguration<Course>
{
    public void Configure(EntityTypeBuilder<Course> entity)
    {
        entity.HasKey(x => x.CourseId);

        entity.HasMany(course => course.Students)
            .WithOne(stud => stud.Course)
            .HasForeignKey(x => x.FKCourseId);

    }
}

编辑:如果你不想在class之间添加,你可能想试试这个:

        entity.HasMany(student => student.Courses)
            .WithMany(course => course.Students)
            .UsingEntity(x => x.Property("StudentsStudentId").HasColumnName("FKStudentId"));

        entity.HasMany(course => course.Students)
            .WithMany(stud => stud.Courses)
            .UsingEntity(x => x.Property("CoursesCourseId").HasColumnName("FKCourseId"));

注:"StudentsStudentId""CoursesCourseId"是按照命名约定生成的。因此,您可能希望先在没有 .UsingEntity() 的情况下添加迁移,然后检查生成的迁移。