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

相关内容

热门资讯

9分钟了解!桂林字牌辅助器,老... 9分钟了解!桂林字牌辅助器,老友十三张有辅助挂吗,可靠教程(有挂脚本);老友十三张有辅助挂吗辅助器中...
8分钟了解!jj斗地主助赢神器... 8分钟了解!jj斗地主助赢神器,金州水鱼免费辅助软件,必胜教程(有挂教学);1、任何金州水鱼免费辅助...
4分钟了解!同城游510k有挂... 4分钟了解!同城游510k有挂吗,同乡游戏有挂吗,高科技教程(有挂解说)1、同城游510k有挂吗透视...
四分钟了解!雀神麻将小程序助赢... 四分钟了解!雀神麻将小程序助赢神器购买,兴动棋牌有挂吗谁用了,分享教程(有挂辅助挂)1、进入游戏-大...
3分钟了解!心悦麻将有挂是真的... 3分钟了解!心悦麻将有挂是真的吗,经典联盟斗牛外挂,攻略教程(有挂软件);进入游戏-大厅左侧-新手福...
三分钟了解!牵手跑胡子辅助工具... 三分钟了解!牵手跑胡子辅助工具,皮皮跑得快辅助器免费版,攻略方法(有挂脚本)1.皮皮跑得快辅助器免费...
8分钟了解!真人天天麻将助赢神... 8分钟了解!真人天天麻将助赢神器,八闽十三张有没有外挂,透明挂教程(有挂规律)1、实时八闽十三张有没...
三分钟了解!邳州友友麻将能调吗... 三分钟了解!邳州友友麻将能调吗,潮汕麻将app有挂吗,黑科技教程(有挂黑科技)进入游戏-大厅左侧-新...
四分钟了解!哥哥打大a有外 挂... 四分钟了解!哥哥打大a有外 挂吗,河洛杠次输赢规律,透明挂教程(有挂秘籍)1)哥哥打大a有外 挂吗辅...
五分钟了解!碣石暗宝外 挂,大... 五分钟了解!碣石暗宝外 挂,大头十三张有没有外挂,教你攻略(有挂规律)1、操作简单,无需注册,只需要...