在ASP.NET MVC中实现多对多连接表的解决方法如下:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public List Courses { get; set; } // 多对多关系
}
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
public List Students { get; set; } // 多对多关系
}
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions options) : base(options)
{
}
public DbSet Students { get; set; }
public DbSet Courses { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity()
.HasMany(s => s.Courses)
.WithMany(c => c.Students)
.UsingEntity(j => j.ToTable("StudentCourse"));
}
}
运行以下命令创建迁移:
dotnet ef migrations add CreateConnectionTable
然后运行以下命令更新数据库:
dotnet ef database update
public class StudentController : Controller
{
private readonly SchoolContext _context;
public StudentController(SchoolContext context)
{
_context = context;
}
public IActionResult Index()
{
var students = _context.Students.Include(s => s.Courses).ToList();
return View(students);
}
}
在视图中可以使用以下方式显示学生和其所选课程:
@model List
@foreach (var student in Model)
{
@student.Name
@foreach (var course in student.Courses)
{
- @course.Name
}
}
这样就可以通过多对多连接表实现ASP.NET MVC中的多对多关系了。