gpt4 book ai didi

c# - Entity Framework Core 中的种子多对多

转载 作者:太空狗 更新时间:2023-10-30 01:29:18 26 4
gpt4 key购买 nike

如何在 EF Core 中播种多对多关系,但在此区域找不到任何内容?

这就是实体

public class Student 
{
public int Id { get; set; }
public string Name { get; set; }

public virtual List<StudentGrade> StudentGrades { get; set; }
}


public class Grade
{
public int Id { get; set; }
public int Grade { get; set; }

public virtual List<StudentGrade> StudentGrades { get; set; }
}


public class StudentGrade
{
public int GradeId { get; set; }
public Grade Grade { get; set; }

public int StudentId { get; set; }
public Student Student { get; set; }
}

所以官方文档说你必须定义一个加入实体(在我的例子中是 StudentGrade),并且应该在多对多关系的实体中引用它。 Ef core documentation for many-to-many .

现在在 EF 中,您不必这样做,它会解决这些问题,因此您无需使用连接实体,只需将每个实体引用到另一个实体即可。

那么如何在 EF Core 中播种这种类型的关系?

谢谢

最佳答案

所以对我有用的是用类似这样的东西覆盖 DbContext::OnModelCreating(ModelBuilder modelBuilder):

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<StudentGrade>()
.HasKey(s => new { s.GradeId , s.StudentId });
var students= new[]
{
new Student{Id=1, Name="John"},
new Student{Id=2, Name="Alex"},
new Student{Id=3, Name="Tom"}
}

var grades = new[]
{
new Grade{Id=1, Grade=5},
new Grade{Id=2, Grade=6}
}

var studentGrades = new[]
{
new StudentGrade{GradeId=1, StudentId=1},
new StudentGrade{GradeId=2, StudentId=2},

// Student 3 relates to grade 1
new StudentGrade{GradeId=1, StudentId=3}
}

modelBuilder.Entity<Student>().HasData(stdudents[0],students[1],students[2]);
modelBuilder.Entity<Grade>().HasData(grades[0],grades[1]);
modelBuilder.Entity<StudentGrade>().HasData(studentGrades[0],studentGrades[1],studentGrades[2]);

base.OnModelCreating( modelBuilder );
}

关于c# - Entity Framework Core 中的种子多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52556363/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com