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

相关内容

热门资讯

wepoke辅助工具的使用教程... wepoke辅助工具的使用教程!wepoke透明挂软件,(We辅poker助)都是存在有挂,揭秘攻略...
wepoke ai辅助!wep... wepoke ai辅助!wepoke有没有玄学,(wepOke)都是是有挂,可靠教程(黑科技脚本)1...
aapoker外挂安全吗!aa... aapoker外挂安全吗!aa poker有外挂吗,(AApOKER)都是真的有挂,透明挂教程(黑科...
wepoke怎么看有没有外挂!... wepoke怎么看有没有外挂!wepoke智能ai什么意思,(wEpOke)切实存在有挂,揭秘教程(...
aapoker辅助软件开发定制... aapoker辅助软件开发定制!aapoker为什么一直输,(AAPOkER)确实是真的有挂,教你教...
AApoker辅助工具!aap... AApoker辅助工具!aapoker辅助软件,(aapokEr)竟然存在有挂,科技教程(黑科技辅助...
wepoke软件能玩吗!wep... wepoke软件能玩吗!wepoke模拟器,(wePOKE)都是有挂,解密教程(黑科技神器)1、进入...
aapoker辅助是什么!aa... aapoker辅助是什么!aapoker透明挂是真的吗,(AApOKER)真是有挂,线上教程(黑科技...
wpk有透视辅助吗!wpk德州... wpk有透视辅助吗!wpk德州ai机器人,(wPk)一直是真的有挂,揭秘教程(黑科技辅助挂)在进入w...
微扑克辅助测试!微扑克专用辅助... 微扑克辅助测试!微扑克专用辅助器,(微扑克)真是真的有挂,透明教程(黑科技工具)1、每一步都需要思考...