Entity Framework Core中处理学生关系表的更佳方案探讨
EF Core映射学生关系:能否保留Dictionary或优化设计?
我有一个Student类,用Relation枚举描述学生间的关系,原本用Dictionary<Student, Relation>存储关系数据:
public class Student { public int Id { get; set; } public string? Name { get; set; } public Dictionary<Student, Relation> Relations { get; set; } = new(); } public enum Relation { None = 0, Friend = 1, Relative = 2 }
我的目标是创建包含students和students_relations两张表的数据库,表结构如下:
students表
| id | name |
|---|---|
| 1 | Tom |
| 2 | Alice |
| 3 | Bob |
students_relations表
| student_id | related_student_id | relation |
|---|---|---|
| 1 | 3 | 1 |
| 3 | 2 | 2 |
| 2 | 3 | 2 |
其中关系是单向的:比如Tom视Bob为Friend,但Bob可能有不同看法,所以表中没有3/1/1的条目;而Relative关系需要双向存储,因此Bob和Alice的对应关系有两条记录。
我正在学习用Entity Framework Core实现这个需求,已知EF Core不支持直接将Dictionary作为属性映射,所以我创建了StudentRelations类:
[PrimaryKey("StudentId", "RelatedStudentId")] public class StudentRelations { [ForeignKey("StudentId")] public Student Student { get; set; } = null!; [ForeignKey("RelatedStudentId")] public Student RelatedStudent { get; set; } = null!; public Relation Relation { get; set; } }
以及ApplicationContext类:
public class ApplicationContext : DbContext { public DbSet<Student> Students { get; set; } = null!; public DbSet<StudentRelations> StudentRelations { get; set; } = null!; protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<StudentRelations>() .HasOne(sr => sr.Student) .WithMany(s => s.Relations); modelBuilder.Entity<StudentRelations>() .HasOne(sr => sr.RelatedStudent); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite("Data Source=students.db") .UseSnakeCaseNamingConvention(); } }
这个方案需要把Student类中的Dictionary改成List<StudentRelations>,虽然能满足需求,但我想知道是否有更优的方案:
- 能否直接将数据库表映射到
Dictionary? - 或者有没有可以优化的数据库设计,不需要使用
Dictionary?
内容的提问来源于stack exchange,提问作者Gigas002
相关产品推荐
相关产品推荐

