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辅助机器人普...
通报开挂!wepoker如何设... 通报开挂!wepoker如何设置透视,天天福建辅助器,开挂(透视)辅助安装(有挂技巧);AI辅助机器...
玩家必备科普"熊猫辅... 玩家必备科普"熊猫辅助官网下载安装"开挂(透视)hhpoker有作弊的吗(确实有挂);简单的透视挂控...
正版辅助!wepoker可以免... 正版辅助!wepoker可以免费玩吗,陕麻圈延安划水辅助,开挂(透视)辅助下载(的确有挂);陕麻圈延...
传授开挂!hhpoker买挂,... 传授开挂!hhpoker买挂,陕麻圈脚本辅助,开挂(透视)辅助工具(有挂教学);亲,有的,ai轻松简...
辅助开挂!牵手辅助神器下载,w... 辅助开挂!牵手辅助神器下载,wepoker私人局辅助器怎么用(透视)开挂辅助下载(讲解有挂)相信很多...
辅助开挂!winner辅助软件... 辅助开挂!winner辅助软件,aapoker俱乐部靠谱吗(透视)开挂辅助插件(有挂工具);亲,有的...
开挂辅助!潘潘讲故事辅助器,德... 开挂辅助!潘潘讲故事辅助器,德普之星透视辅助软件(透视)开挂辅助神器(存在有挂);1、让任何用户在无...
曝光辅助!来玩德州破解器,指尖... 曝光辅助!来玩德州破解器,指尖辅助,开挂(透视)辅助软件(有挂秘籍);亲,有的,ai轻松简单,又可以...
开挂辅助!天天爱柳州辅助,we... 开挂辅助!天天爱柳州辅助,wepoker私人辅助器(透视)开挂辅助插件(有挂讲解);1、超多福利:超...