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

相关内容

热门资讯

十分钟总结!中至赣牌圈为什么老... 十分钟总结!中至赣牌圈为什么老是输,微扑克ai人工智能(详细透视辅助软件教程)是由北京得中至赣牌圈为...
九分钟详情!川麻圈辅助软件在哪... 九分钟详情!川麻圈辅助软件在哪里买,wpk有(详细透视辅助黑科技教程)准备好在川麻圈辅助软件在哪里买...
五分钟黑科技!闲趣麻将有什么猫... 五分钟黑科技!闲趣麻将有什么猫腻,红龙扑克会作假(详细透视辅助挂教程)是一款可以让一直输的玩家,快速...
九分钟了解!雀神辅助器最新款,... 九分钟了解!雀神辅助器最新款,轰趴大菠萝十三水有外 挂(详细透视辅助神器教程);雀神辅助器最新款最新...
四分钟介绍!wepoke辅助技... 四分钟介绍!wepoke辅助技巧,德州之星ai辅助(详细透视辅助插件教程)wepoke辅助技巧平台为...
八分钟攻略!永州四王扯胡子包赢... 八分钟攻略!永州四王扯胡子包赢,众合推扑克辅助工具(详细透视辅助软件教程)1、这是跨平台的永州四王扯...
五分钟透明!双辽麻将有挂吗,微... 《软件透明挂》是一款多人竞技的辅助透视游戏,你将微扑克对手来到同一个战场,为至高无上的荣耀进行一次自...
we辅助poker德之星!we... we辅助poker德之星!wepoke有假吗(wepoke好友房)切实是真的有挂(详细智能ai教程)...
WePoKe透明挂!wepok... WePoKe透明挂!wepoke德州扑克系统规律(wepoke app)一直存在有挂(详细透视挂教程...
微扑克辅助挂!微扑克wpk安全... 《微扑克辅助挂软件透明挂》是一款多人竞技的微扑克辅助挂辅助透视游戏,你将微扑克对手来到同一个战场,为...