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

相关内容

热门资讯

记者揭秘!新超圣正版辅助,新老... 新超圣正版辅助是一款专注玩家量身打造的游戏记牌类型软件,在新超圣正版辅助这款游戏中我们可以记录下每张...
透视游戏!aapoker怎么设... 透视游戏!aapoker怎么设置抽水,pokemmo脚本辅助器(辅助挂)详细开挂辅助安装;亲,aap...
科普分享!新超凡手游辅助,心悦... 您好:心悦踢坑辅助器这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特...
透视有挂!乐享麻将连连看辅助,... 透视有挂!乐享麻将连连看辅助,hhpoker万能辅助器(辅助挂)详细开挂辅助软件;无需打开直接搜索薇...
总算了解!越悦游戏字牌攻略,牵... 您好:这款越悦游戏字牌攻略游戏是可以开挂的,确实是有挂的,很多玩家在这款越悦游戏字牌攻略游戏中打牌都...
透视好牌!微乐小程序外辅助工具... 透视好牌!微乐小程序外辅助工具,约局吧开挂神器是真的吗(辅助挂)详细开挂辅助下载 了解更多开挂安装加...
来一盘!微信随意玩辅助器,51... 【亲,微信随意玩辅助器 这款游戏可以开挂的,确实是有挂的,很多玩家在这款微信随意玩辅助器中打牌都会发...
透明科技!开心泉州小程序工具,... 透明科技!开心泉州小程序工具,aapoker免费透视脚本(辅助挂)详细开挂辅助工具您好:开心泉州小程...
专业讨论!丽水茶苑游戏辅助,抓... 专业讨论!丽水茶苑游戏辅助,抓住捣蛋鸡开挂(有挂功能开挂辅助安装) 了解更多开挂安装加(136704...
透视好友!天天贵阳破解版,有没... 您好:这款天天贵阳破解版游戏是可以开挂的,确实是有挂的,很多玩家在这款天天贵阳破解版游戏中打牌都会发...