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

相关内容

热门资讯

2分钟细说“wepoker开挂... >>您好:wepoker开挂辅助方法确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别好...
盘点几款“wpk辅助挂”开挂辅... 盘点几款“wpk辅助挂”开挂辅助器(透视)力荐教程是一款可以让一直输的玩家,快速成为一个“必胜”的a...
热点推荐“wepoker能不能... wepoker能不能开挂是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可...
最新技巧“wepokerpus... 无需打开直接搜索;操作使用教程:最新技巧“wepokerpus透视挂是真的假的”开挂辅助软件(透视)...
科技介绍“wepoker透视软... wepoker透视软件挂教程是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用...
终于清楚“wePoKer有透视... >>您好:wePoKer有透视软件吗软件加扣扣群确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用...
科技通报“wepoker能不能... >>>您好:,软件加微信【添加136704302】确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...
传递经验“微扑克透牌”开挂辅助... >>>您好:,软件加微信【添加136704302】确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...
一分钟带你了解“微扑克发牌规律... >>您好:微扑克发牌规律软件加扣扣群确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别好...
一起来探讨“wepoker机制... 您好:wepoker机制发冤家牌这款游戏是可以开挂的,软件加【添加微信客服136704302】确实是...