ASP.NETMVC中使用存储库模式实现多对多关系。
创始人
2024-09-19 09:30:49
0
  1. 创建实体类

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

public class Course { public int Id { get; set; } public string Name { get; set; } public virtual ICollection Students { get; set; } }

  1. 创建DbContext

public class ApplicationDbContext : DbContext { public DbSet Students { get; set; } public DbSet Courses { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity()
        .HasMany(s => s.Courses)
        .WithMany(c => c.Students)
        .Map(cs =>
        {
            cs.MapLeftKey("StudentId");
            cs.MapRightKey("CourseId");
            cs.ToTable("StudentCourses");
        });
}

}

  1. 创建存储库

public class CourseRepository : IDisposable { private ApplicationDbContext context = new ApplicationDbContext();

public void AddCoursesToStudent(Student student, List courses)
{
    student.Courses = courses;
    context.SaveChanges();
}

public List GetCoursesForStudent(int studentId)
{
    return context.Students
        .Where(s => s.Id == studentId)
        .SelectMany(s => s.Courses)
        .ToList();
}

public void Dispose()
{
    context.Dispose();
}

}

  1. 控制器和视图

public class HomeController : Controller { private CourseRepository courseRepository = new CourseRepository();

public ActionResult Index()
{
    ViewBag.Courses = courseRepository.GetCoursesForStudent(1);
    return View();
}

[HttpPost]
public ActionResult SaveCourses()
{
    int studentId = int.Parse(Request.Form["studentId"]);
    List courses = Request.Form["courses"]
        .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
        .Select(courseId => new Course { Id = int.Parse(courseId) })
        .ToList();

    courseRepository.AddCoursesToStudent(studentId, courses);
    return RedirectToAction("Index");
}

}

@model ProjectName.Models.Student

@{ ViewBag.Title = "Index";

相关内容

热门资讯

透视技法!wepoker究竟有... 透视技法!wepoker究竟有没有透视(德普之星设置)本来有辅助技巧(哔哩哔哩)wepoker究竟有...
透视要领!wejoker辅助机... 透视要领!wejoker辅助机器人(HHpoker教程)其实真的是有辅助插件(哔哩哔哩)wejoke...
透视攻略!拱趴大菠萝机器人(H... 透视攻略!拱趴大菠萝机器人(HHpoker插件)其实真的是有辅助技巧(哔哩哔哩)1、每一步都需要思考...
透视讲义!wepoker可以开... 透视讲义!wepoker可以开透视吗(HHpoker脚本挂)总是是有辅助教程(哔哩哔哩)1、wepo...
透视操作!xpoker透视辅助... 透视操作!xpoker透视辅助(HHpoker有辅助)本来是真的有辅助脚本(哔哩哔哩)1、打开软件启...
透视学习!红龙poker辅助平... 透视学习!红龙poker辅助平台(WePoKer看底牌)一直有辅助方法(哔哩哔哩)1.红龙poker...
透视方针!hhpoker俱乐部... 透视方针!hhpoker俱乐部是干嘛的(HHpoker辅助挂)一贯真的是有辅助教程(哔哩哔哩)1、每...
透视指南!德扑之心免费透视(W... 透视指南!德扑之心免费透视(WePoKer用挂)好像真的是有辅助攻略(哔哩哔哩)小薇(辅助器软件下载...
透视方式!pokemmo脚本辅... 透视方式!pokemmo脚本辅助(WePoKer私人局)本来是真的有辅助软件(哔哩哔哩)1、poke...
透视绝活!HH平台挂(AApo... 透视绝活!HH平台挂(AApoker控制牌)一直真的是有辅助技巧(哔哩哔哩)1)HH平台挂辅助插件:...