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

相关内容

热门资讯

必看攻略!途游辅助器软件,榕城... 必看攻略!途游辅助器软件,榕城50k辅助,细节开挂辅助教程(有挂分析);无需打开直接搜索加(薇:13...
玩家必看教程!海贝大厅辅助下载... 玩家必看教程!海贝大厅辅助下载,欢聚水鱼智能辅助教程,教会开挂辅助教程(有挂解密);无需打开直接搜索...
玩家必看!微信小程序多功能辅助... 玩家必看!微信小程序多功能辅助,欢乐达人暗宝源码,科技开挂辅助教程(有挂讲解);无需打开直接搜索打开...
终于清楚!小程序牵手跑得辅助,... 终于清楚!小程序牵手跑得辅助,随意玩有辅助吗,分享开挂辅助教程(有挂细节);无需打开直接搜索加(薇:...
实测必看!福麻圈跑得快辅助功能... 实测必看!福麻圈跑得快辅助功能,战神辅助官方,关于开挂辅助教程(有挂技术);无需打开直接搜索薇:13...
重大发现!新海豚辅助工具,九酷... 您好:新海豚辅助工具这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特...
一分钟教会你!财神十三张脚本效... 一分钟教会你!财神十三张脚本效果图,川友汇辅助软件,传授开挂辅助教程(有挂教学);无需打开直接搜索加...
必备科技!闲来辅助器免费,四川... 必备科技!闲来辅助器免费,四川徒有辅助软件,发现开挂辅助教程(有挂工具);无需打开直接搜索打开薇:1...
一分钟揭秘!福建十三水辅助,越... 一分钟揭秘!福建十三水辅助,越乡游辅助器,通报开挂辅助教程(有挂功能);无需打开直接搜索加(薇:13...
总算了解!科乐填大坑作弊视频,... 总算了解!科乐填大坑作弊视频,威信茶馆解码器,关于开挂辅助教程(有人有挂);无需打开直接搜索加薇13...