Fluent API 一对多关系的配置
Fluent API Configuration of One-To-Many relationship
配置一对多关系时,我通常“仅”从一侧配置关系。但是我想知道从双方配置关系会有什么效果?这是丰富的、模棱两可的还是有任何有意义的影响?
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
配置一对多关系时,我通常“仅”从一侧配置关系。但是我想知道从双方配置关系会有什么效果?这是丰富的、模棱两可的还是有任何有意义的影响?
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