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作弊最怕三个东... 透视系统!wpk作弊最怕三个东西,wpk模拟器是什么,详细教程(有挂技巧)1、wpk作弊最怕三个东西...
透视模拟器!wpk有辅助器吗,... 透视模拟器!wpk有辅助器吗,wpk官网下载链接,实用技巧(有挂解密)1、wpk官网下载链接透视辅助...
透视游戏!有哪些免费的wpk作... 透视游戏!有哪些免费的wpk作弊码,wpk俱乐部有没有辅助,微扑克教程(有挂解说);1)有哪些免费的...
透视有挂!wpk辅助购买,wp... 透视有挂!wpk辅助购买,wpk辅助,AI教程(有挂细节)1、用户打开应用后不用登录就可以直接使用,...
透视免费!wpk德州局怎么透视... 透视免费!wpk德州局怎么透视,wpk有作弊吗,玩家教程(有挂细节)1、起透看视 wpk德州局怎么透...
透视透视!wpk辅助插件,wp... 透视透视!wpk辅助插件,wpk有作弊吗,AI教程(有挂技巧)1)wpk有作弊吗辅助挂:进一步探索w...
透视有挂!wpk德州局怎么透视... 透视有挂!wpk德州局怎么透视,wpk私人辅助,插件教程(有挂介绍)1、wpk德州局怎么透视系统规律...
透视智能ai!wpk控制牌是真... 透视智能ai!wpk控制牌是真的吗,wpk德州局怎么透视,黑科技教程(有挂规律);1、点击下载安装,...
透视规律!wpk可以作弊吗,w... 透视规律!wpk可以作弊吗,wpk德州局透视,安装教程(有挂教程)1、金币登录送、破产送、升级送、活...
透视系统!wpk辅助,wpk作... 透视系统!wpk辅助,wpk作弊是真的吗,大神讲解(有挂工具)1、完成wpk作弊是真的吗透视辅助安装...