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

相关内容

热门资讯

每日必看!微信蜀山四川修改器,... 每日必看!微信蜀山四川修改器,hhpoker软件可以玩吗,透明挂教程(果真有挂);微信蜀山四川修改器...
一分钟了解!逗娱碰胡辅助器,h... 【福星临门,好运相随】;一分钟了解!逗娱碰胡辅助器,hhpoker透视方法,辅助教程(揭秘有挂);暗...
我来分享!新畅游插件,werp... 您好:新畅游插件这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别好...
玩家必看教程!聚友联盟辅助器,... 玩家必看教程!聚友联盟辅助器,hhpoker免费透视脚本,AA德州教程(的确有挂);玩家必看教程!聚...
实测必看!大唐辅助软件,wep... 您好:大唐辅助软件这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别...
分享认知!拱趴辅助,菠萝辅助器... 您好,菠萝辅助器这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在这款游...
玩家必知教程!边锋干瞪眼开挂,... 玩家必知教程!边锋干瞪眼开挂,wepoker透视脚本免费下载pc,教你攻略(证实有挂)是一款可以让一...
我来向大家传授!乐乐游戏辅助器... 我来向大家传授!乐乐游戏辅助器,wepoker挂,安装教程(有挂工具);相信小伙伴都知道这个乐乐游戏...
热点讨论!逗娱碰胡辅助器,hh... 热点讨论!逗娱碰胡辅助器,hhpoker透视方法,总结教程(有挂教程);逗娱碰胡辅助器软件透明挂更新...
玩家必看科普!维系小程序雀神挂... 您好:维系小程序雀神挂件这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的...