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

相关内容

热门资讯

出现新变化!福建大玩家辅助操作... 您好:福建大玩家辅助操作视频这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用...
第九分钟开挂!微信小程序微乐挖... 第九分钟开挂!微信小程序微乐挖坑辅助免费,花花生活圈可以开挂,教你教程-2026最新版本微信小程序微...
此事引发广泛关注!三哥玩摆头注... 此事引发广泛关注!三哥玩摆头注可以控制(辅助挂)其实是有挂(有挂法门)-哔哩哔哩 【无需打开直接搜索...
九分钟开挂!皮皮透视辅助软件工... 九分钟开挂!皮皮透视辅助软件工具,皇豪互众控制系统下载,分享教程-2026最新版本1、九分钟开挂!皮...
今天上午!蜀山四川辅助脚本(辅... 今天上午!蜀山四川辅助脚本(辅助挂)一直真的有挂(有挂方案)-哔哩哔哩;亲,蜀山四川辅助脚本这款游戏...
四分钟开挂!闲逸同花插件,欢聚... 四分钟开挂!闲逸同花插件,欢聚水鱼辅助视频,必备教程-2026最新版本1、欢聚水鱼辅助视频透视辅助简...
为切实保障!牌乐门安全黑科技是... 为切实保障!牌乐门安全黑科技是真的吗(辅助挂)其实真的是有挂(有挂方针)-哔哩哔哩您好:牌乐门安全黑...
五分钟开挂!约局吧辅助器下载,... 五分钟开挂!约局吧辅助器下载,兴动互娱辅助工具,介绍教程-2026最新版本1、该软件可以轻松地帮助玩...
据了解!今日长牌破解(辅助挂)... 据了解!今日长牌破解(辅助挂)原来是有挂的(有挂机巧)-哔哩哔哩 了解更多开挂安装加(1367043...
3分钟开挂!广西老友玩友破解视... 3分钟开挂!广西老友玩友破解视频,玄龙辅助工具,教你教程-2026最新版本1)广西老友玩友破解视频辅...