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

相关内容

热门资讯

现就发布提示!红龙poker辅... 现就发布提示!红龙poker辅助(透视)微乐小程序透视工具(真是是真的辅助修改器)-哔哩哔哩1、很好...
透视透视挂!aapoker辅助... 透视透视挂!aapoker辅助软件合法吗(透视)好友赣南能装挂吗(确实有辅助安装)-哔哩哔哩1、这是...
透视线上!wepoker辅助器... 透视线上!wepoker辅助器有哪些功能(透视)新蜜瓜房卡大厅辅助科技(一直是真的辅助app)-哔哩...
最终!wepoker破解器有用... 最终!wepoker破解器有用吗(透视)九哥玩辅助软件安装(真是真的有辅助下载)-哔哩哔哩1、进入游...
截至目前!pokermaste... 截至目前!pokermaster脚本(透视)越乡游义乌透视下载(一直真的是有辅助插件)-哔哩哔哩1)...
据报道!wepoker有没有插... 据报道!wepoker有没有插件(透视)人人燕赵辅助(确实真的是有辅助平台)-哔哩哔哩1、起透看视 ...
透视辅助!hardrock透视... 透视辅助!hardrock透视工具(透视)微乐手游微乐辅助免费(本来是有辅助平台)-哔哩哔哩1、操作...
突发!xpoker辅助神器(透... 突发!xpoker辅助神器(透视)微信途游四川小程序脚本(果然存在有辅助插件)-哔哩哔哩1、进入到微...
透视透视!拱趴大菠萝万能辅助器... 透视透视!拱趴大菠萝万能辅助器(透视)微信游戏决胜游戏辅助(都是存在有辅助下载)-哔哩哔哩进入游戏-...
今日!拱趴大菠萝万能挂图解(透... 今日!拱趴大菠萝万能挂图解(透视)南通长牌有挂吗(好像真的是有辅助下载)-哔哩哔哩1、今日!拱趴大菠...