You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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表

idname
1Tom
2Alice
3Bob

students_relations表

student_idrelated_student_idrelation
131
322
232

其中关系是单向的:比如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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 13:17:14