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正确养号方法-原先有挂开挂辅助软件1、下载安装好小程序牵...
透明新版!传送屋透视,wepo... 传送屋透视开挂教程视频分享装挂详细步骤在当今的网络游戏中,传送屋透视作为一种经典的娱乐方式,吸引了无...
透视智能ai!友玩广西修改器,... 透视智能ai!友玩广西修改器,哈糖大菠萝怎么开挂-固有有挂开挂辅助挂;无需打开直接搜索加薇13670...
透视线上!山西打锅子技巧,aa... 透视线上!山西打锅子技巧,aa poker辅助-原先有挂开挂辅助挂 了解更多开挂安装加(136704...
透明软件!逍遥辅助器怎么用,a... 透明软件!逍遥辅助器怎么用,aapoker透视脚本-本然有挂开挂辅助工具这是一款可以让一直输的玩家,...
透明规律!老友广东辅助工具下载... 【亲,老友广东辅助工具下载地址 这款游戏可以开挂的,确实是有挂的,很多玩家在这款老友广东辅助工具下载...
透明讲解!微信小程序财神破解版... 微信小程序财神破解版是一款专注玩家量身打造的游戏记牌类型软件,在微信小程序财神破解版这款游戏中我们可...
透视规律!小闲川南辅助,wep... 小闲川南辅助开挂教程视频分享装挂详细步骤在当今的网络游戏中,小闲川南辅助作为一种经典的娱乐方式,吸引...
透视模拟器!决战卡五星游戏辅助... 决战卡五星游戏辅助是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以加我...
透明有挂!四川乐易麻将辅助脚本... 大家好,今天小编来为大家解答四川乐易麻将辅助脚本这个问题咨询软件客服可以免费测试直接加微信(1367...