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

相关内容

热门资讯

透视讲解!wpk私人局有透视吗... 您好,wepoker透视辅助下载这款游戏可以开挂的,确实是有挂的,需要了解加去威信【13670430...
透视app!红龙poker有辅... 透视app!红龙poker有辅助吗(透视)开挂辅助器(果然存在有挂)-哔哩哔哩所有人都在同一条线上,...
透视辅助!epoker透视底牌... 透视辅助!epoker透视底牌,哈糖大菠萝开挂,阶段教程(总是是有挂)-哔哩哔哩1、玩家可以在哈糖大...
透视插件!wepoker辅助器... 透视插件!wepoker辅助器激活码(透视)开挂辅助器(其实有挂)-哔哩哔哩1)wepoker辅助器...
透视教程!hhpoker德州挂... 透视教程!hhpoker德州挂真的有吗,werplan透视挂,学习教程(一贯存在有挂)-哔哩哔哩1、...
透视游戏!aapoker免费透... 透视游戏!aapoker免费透视脚本,xpoker辅助工具,诀窍教程(一贯存在有挂)-哔哩哔哩1)a...
透视大厅!aa poker透视... 透视大厅!aa poker透视软件(透视)开挂辅助器(原来是有挂)-哔哩哔哩1、超多福利:超高返利,...
透视脚本!xpoker辅助工具... 透视脚本!xpoker辅助工具,pokernow辅助工具,方案教程(一贯真的有挂)-哔哩哔哩1、不需...
透视修改器!wepoker透视... 透视修改器!wepoker透视有吗(透视)开挂辅助神器(竟然是有挂)-哔哩哔哩wepoker透视有吗...
透视科技!wejoker透视方... 透视科技!wejoker透视方法,wepoker线上大神,操作教程(确实存在有挂)-哔哩哔哩在进入w...