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

相关内容

热门资讯

第四分钟辅助!新西部大厅辅助,... 第四分钟辅助!新西部大厅辅助,天蝎辅助(推荐攻略开挂辅助神器);1、超多福利:超高返利,海量正版游戏...
四分钟辅助!pokernow辅... 四分钟辅助!pokernow辅助工具,九九联盟辅助教程(一分钟揭秘开挂辅助安装);九九联盟辅助教程中...
六分钟辅助!微信小程序多乐辅助... 六分钟辅助!微信小程序多乐辅助器,丽水茶苑苹果手机辅助(分享认知开挂辅助插件);微信小程序多乐辅助器...
第2分钟辅助!wepoker破... 第2分钟辅助!wepoker破解器有用吗,点点游戏辅助(一分钟了解开挂辅助脚本);详细点点游戏辅助攻...
第三分钟辅助!全民比鸡bug,... 第三分钟辅助!全民比鸡bug,天天微友可以控制吗(分享开挂内幕开挂辅助脚本);天天微友可以控制吗最新...
第八分钟辅助!wepoker怎... 第八分钟辅助!wepoker怎么买辅助,微信小程序加速脚本(技术分享开挂辅助脚本);相信小伙伴都知道...
第九分钟辅助!赣牌圈挂怎么安装... 第九分钟辅助!赣牌圈挂怎么安装,雀神广东麻将透视视频(发现一款开挂辅助软件);1、很好的雀神广东麻将...
第6分钟辅助!浙江宝宝游戏辅助... 第6分钟辅助!浙江宝宝游戏辅助器,博雅棋牌辅助器(实测揭晓开挂辅助工具);1、完成博雅棋牌辅助器的残...
第2分钟辅助!飞驰娱乐软件科技... 第2分钟辅助!飞驰娱乐软件科技,欢乐游戏城攻略(透视了解开挂辅助插件);大家肯定在之前飞驰娱乐软件科...
1分钟辅助!微友三代辅助,新超... 1分钟辅助!微友三代辅助,新超圣辅助靠谱不(必备教程开挂辅助脚本);1、这是跨平台的新超圣辅助靠谱不...