问题描述
在配置一对多关系时,我通常“仅”从一侧配置关系。但我想知道从双方配置关系会产生什么影响?这是丰富的、模棱两可的还是有任何有意义的影响?
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int CurrentGradeId { get; set; }
public Grade Grade { get; set; }
}
public class Grade
{
public int GradeId { get; set; }
public string GradeName { get; set; }
public string Section { get; set; }
public ICollection<Student> Students { get; set; }
}
流畅的 API 配置
public class StudentConfiguration : IEntityTypeConfiguration<Student>
{
public void Configure(EntityTypeBuilder<Student> builder)
{
builder
.ToTable("Students")
.HasKey(p => p.Id);
builder
.HasOne(student => student.Grade)
.WithMany(grade => grade.Students)
.HasForeignKey(student => student.CurrentGradeId)
}
}
public class GradeConfiguration : IEntityTypeConfiguration<Grade>
{
public void Configure(EntityTypeBuilder<Grade> builder)
{
builder
.ToTable("Grades")
.HasKey(p => p.GradeId);
builder
.HasMany(grade => grade.Students)
.WithOne(student => student.Grade)
.HasForeignKey(student => student.CurrentGradeId)
}
}
解决方法
两者都可以。但不能两者兼而有之。 (尽管您似乎交换了“Has...”代码块)。
https://www.learnentityframeworkcore.com/configuration/one-to-many-relationship-configuration