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. 在更新操作完成后,重定向到合适的视图页面。

相关内容

热门资讯

外挂指南!红龙poker辅助,... 外挂指南!红龙poker辅助,佛手大菠萝13道挂哪里-本来一直总是有辅助脚本(哔哩哔哩)一、佛手大菠...
外挂资料!哈糖大菠萝有挂吗,p... 外挂资料!哈糖大菠萝有挂吗,pokernow辅助工具-真是存在有辅助app(哔哩哔哩)1、每一步都需...
外挂演示!哈糖大菠萝能开挂吗,... 外挂演示!哈糖大菠萝能开挂吗,pokerworld破解版下载-果然真的有辅助方法(哔哩哔哩)哈糖大菠...
外挂办法!xpoker透视辅助... 外挂办法!xpoker透视辅助,佛手在线大菠萝辅助-本来有辅助教程(哔哩哔哩)1、佛手在线大菠萝辅助...
外挂学习!德州局透视脚本免费版... 外挂学习!德州局透视脚本免费版下载手机版,来玩app破解版-确实是真的有辅助技巧(哔哩哔哩)1、每一...
外挂学习!xpoker辅助助手... 外挂学习!xpoker辅助助手,哈糖大菠萝软件下载-一直一直都是有辅助脚本(哔哩哔哩)1、下载好哈糖...
外挂教程书!拱趴大菠萝万能辅助... 外挂教程书!拱趴大菠萝万能辅助器,拱趴大菠萝有挂吗-果然一直总是有辅助工具(哔哩哔哩)1、每一步都需...
外挂练习!poker红龙辅助,... 外挂练习!poker红龙辅助,约局吧开挂-真是存在有辅助技巧(哔哩哔哩)poker红龙辅助透视方法中...
外挂学习!werplan有挂吗... 外挂学习!werplan有挂吗,德普之星透视辅助-好像真的有辅助脚本(哔哩哔哩)运werplan有挂...
外挂指南!pokernow辅助... 您好,pokernow辅助工具这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054...