ASPMVCEntityFrameworkcore.Updatemanytomanyrelationshiponformpost
创始人
2024-09-20 04:30:48
0
  1. 首先在数据库中创建一个关系表(中间表)以保存多对多关系。
  2. 在模型类中声明关系,例如:
public class Student
{
   public int StudentId { get; set; }
   public string Name { get; set; }

   public ICollection Courses { get; set; }
}

public class Course
{
   public int CourseId { get; set; }
   public string Title { get; set; }

   public ICollection Students { get; set; }
}
  1. 在上述模型中使用 [ForeignKey] 和 [InverseProperty] 属性来指定相应的外键和反向导航属性。确保通过中间表建立正确的多对多关系。
  2. 在视图中使用 @Html.HiddenFor 和 @Html.CheckBoxFor 显示对应关系的数据和状态。
  3. 在控制器中,执行上述关系的更新操作,例如:
[HttpPost]
public IActionResult Edit(int studentId, List selectedCourseIds)
{
    Student student = _context.Students
        .Include(s => s.Courses)
        .Single(s => s.StudentId == studentId);

    student.Courses = new List();
    if (selectedCourseIds != null)
    {
        foreach (int courseId in selectedCourseIds)
        {
            Course course = _context.Courses.Find(courseId);
            student.Courses.Add(course);
        }
    }

    _context.SaveChanges();

    return RedirectToAction("Index");
}
  1. 在更新操作完成后,重定向到合适的视图页面。

相关内容

热门资讯

透视辅助!wepoker私人辅... 透视辅助!wepoker私人辅助器,hhpoker有辅助的吗,经验教程(切实是真的挂)-哔哩哔哩1、...
透视透视!来玩德州破解器,ag... 透视透视!来玩德州破解器,agpoker辅助,教程书教程(一直真的有挂)-哔哩哔哩1、来玩德州破解器...
透视存在!wejoker辅助软... 透视存在!wejoker辅助软件视频,aapoker能控制牌吗,举措教程(一直真的有挂)-哔哩哔哩w...
透视脚本!wpk俱乐部是真的吗... 透视脚本!wpk俱乐部是真的吗,wpk透视辅助靠谱吗,模块教程(一贯真的有挂)-哔哩哔哩1、下载好w...
透视辅助!wpk透视怎么安装,... 透视辅助!wpk透视怎么安装,哈糖大菠萝软件下载,技法教程(真是有挂)-哔哩哔哩1)哈糖大菠萝软件下...
透视了解!wepoker私人局... 透视了解!wepoker私人局透视,aapoker怎么设置抽水,演示教程(都是是真的挂)-哔哩哔哩1...
透视有挂!wepoker免费脚... 透视有挂!wepoker免费脚本,poker world辅助器,绝活儿教程(本来真的是有挂)-哔哩哔...
透视肯定!aapoker破解侠... 透视肯定!aapoker破解侠是真的吗,wepoker私人局怎么玩,方式教程(总是是有挂)-哔哩哔哩...
透视插件!来玩app 德州 辅... 透视插件!来玩app 德州 辅助,约局吧如何查看是否有挂,教程书教程(一贯是有挂)-哔哩哔哩一、约局...
透视辅助!wepoker软件辅... 透视辅助!wepoker软件辅助程序,wepoker辅助器下载,总结教程(原来存在有挂)-哔哩哔哩1...