【发布时间】:2021-09-20 12:06:07
【问题描述】:
如何阻止 EF Core 创建这样的名称?我有一张包含学生和锻炼的表格,我让他们为 EF Core 设置了链接表。我正在使用 EF Core 5.09。我正在关注本书的示例
https://www.learnentityframeworkcore.com/configuration/one-to-many-relationship-configuration
但我认为如果它创建了这样的名称会出现问题
public class StudentClasses
{
public int StudentId { get; set; }
public Students Students { get; set; }
public int ClassId { get; set; }
public Classes Classes { get; set; }
}
然后在OnModelCreating 覆盖中,我有以下内容:
modelBuilder.Entity<StudentClasses>()
.HasKey(bc => new { bc.StudentId, bc.ClassId });
modelBuilder.Entity<StudentClasses>()
.HasOne(bc => bc.Students)
.WithMany(b => b.StudentClasses)
.HasForeignKey(bc => bc.StudentId);
modelBuilder.Entity<StudentClasses>()
.HasOne(bc => bc.Classes)
.WithMany(c => c.StudentClasses)
.HasForeignKey(bc => bc.ClassId);
但这会导致数据库中的命名约定很糟糕。
如何让它只显示ClassId 作为外键的名称我修复了代码中的拼写错误,但我不知道如何停止它之前的类。这是一个学生可以属于多个班级的关系。
我的学生班级
public class Students
{
[Key]
public int StudentId { get; set; }
public int? Type { get; set; }
public string? FirstName { get; set; }
public string? Surname { get; set; }
public DateTime? DOB { get; set; }
public decimal? Weight { get; set; }
public decimal? Height { get; set; }
public int? Gender { get; set; }
public string? Age { get; set; }
public ICollection<StudentWorkouts> StudentWorkouts { get; set; }
public ICollection<StudentClasses> StudentClasses { get; set; }
public bool? IsDeleted { get; set; }
public bool? IsActive { get; set; }
public string? CreatedBy { get; set; }
public string? LastModifiedBy { get; set; }
public DateTime? LastUpdatedDate { get; set; }
public DateTime? CreatedDate { get; set; }
}
我的Classes 班级 - 没有双关语:
public class Classes
{
[Key]
public int ClassedId { get; set; }
public Guid? UserId { get; set; }
public ICollection<Students> Students { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public ICollection<StudentClasses> StudentClasses { get; set; }
public bool? IsDeleted { get; set; }
public bool? IsActive { get; set; }
public string? CreatedBy { get; set; }
public string? LastModifiedBy { get; set; }
public DateTime? LastUpdatedDate { get; set; }
public DateTime? CreatedDate { get; set; }
}
【问题讨论】:
-
我不明白那个外键是干什么用的,因为你有一个多对多表。我想你可以删除它。它必须来自之前的数据库结构。
-
为什么你的
Classes有Students导航?这就是 EF Core 生成新影子属性的原因。您是否要定义跳过导航? (docs.microsoft.com/en-us/ef/core/modeling/…) -
不,我不想跳过它,我正在关注该教程