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";

相关内容

热门资讯

如何分辨真伪!微乐江苏小程序游... 如何分辨真伪!微乐江苏小程序游戏破解下载,新上游辅助,可靠教程(有挂教程);无需打开直接搜索加(薇:...
重大推荐!开心斗一番破解版,呱... 重大推荐!开心斗一番破解版,呱呱丰城双剑辅助,力荐教程(有挂秘笈);无需打开直接搜索加薇136704...
解密关于!青鸟辅助怎么更新,蜀... 您好:蜀山四川辅助脚本这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌...
玩家必备科技!心悦填大坑辅助器... 玩家必备科技!心悦填大坑辅助器免费版,皇豪互娱控制系统,第三方教程(有挂工具)1、下载安装好心悦填大...
一分钟了解!微信随意玩辅助器,... 一分钟了解!微信随意玩辅助器,518互游辅助,细节揭秘(真实有挂);无需打开直接搜索加(薇:1367...
今日公布!川滇互娱app辅助,... 今日公布!川滇互娱app辅助,反杀新火神辅助,解密教程(有挂分析);无需打开直接搜索加(薇:1367...
指导大家!广东闲来游戏辅助,朱... 您好:广东闲来游戏辅助这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌...
一分钟揭秘!福建大菠萝辅助透视... 一分钟揭秘!福建大菠萝辅助透视,四川家园辅助软件,黑科技教程(有挂分享)1、下载安装好福建大菠萝辅助...
玩家交流!一起宁德吊蟹辅助,杭... 玩家交流!一起宁德吊蟹辅助,杭州都莱辅助软件,教你教程(有挂教程);无需打开直接搜索加(薇:1367...
盘点一款!决战卡五星挂怎么弄,... 盘点一款!决战卡五星挂怎么弄,掌电竞技辅助器,AI教程(有挂方针);无需打开直接搜索加(薇:1367...