EF Core 2.1是Entity Framework Core的一个版本,它是一个轻量级、跨平台的对象关系映射(ORM)框架,用于在.NET应用程序中与数据库进行交互。在EF Core 2.1中,可以使用以下步骤来映射具有相同类型的多对多关系:
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public ICollection<StudentCourse> StudentCourses { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string Name { get; set; }
public ICollection<StudentCourse> StudentCourses { get; set; }
}
public class StudentCourse
{
public int StudentId { get; set; }
public Student Student { get; set; }
public int CourseId { get; set; }
public Course Course { get; set; }
}
public class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<StudentCourse>()
.HasKey(sc => new { sc.StudentId, sc.CourseId });
modelBuilder.Entity<StudentCourse>()
.HasOne(sc => sc.Student)
.WithMany(s => s.StudentCourses)
.HasForeignKey(sc => sc.StudentId);
modelBuilder.Entity<StudentCourse>()
.HasOne(sc => sc.Course)
.WithMany(c => c.StudentCourses)
.HasForeignKey(sc => sc.CourseId);
}
}
var student = new Student { Name = "John" };
var course = new Course { Name = "Math" };
context.Students.Add(student);
context.Courses.Add(course);
student.StudentCourses.Add(new StudentCourse { Course = course });
course.StudentCourses.Add(new StudentCourse { Student = student });
context.SaveChanges();
以上是EF Core 2.1中映射具有相同类型的多对多关系的基本步骤。对于更复杂的情况,可以使用其他配置选项和技术来满足需求。关于EF Core的更多信息和使用方法,可以参考腾讯云的相关产品文档:EF Core 2.1 文档。
领取专属 10元无门槛券
手把手带您无忧上云