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

相关内容

热门资讯

3分钟教程书!aapoker透... 3分钟教程书!aapoker透视方法(透视)果然有辅助透视(哔哩哔哩)1、aapoker透视方法有没...
第9分钟步骤!WePoKer辅... 第9分钟步骤!WePoKer辅助器(透视)一直是有辅助插件(哔哩哔哩)1、第9分钟步骤!WePoKe...
七分钟机巧!wejoker手机... 七分钟机巧!wejoker手机版透视脚本(透视)竟然真的有辅助透视(哔哩哔哩)1、七分钟机巧!wej...
第九分钟机巧!德州真人透视脚本... 第九分钟机巧!德州真人透视脚本(透视)确实存在有辅助工具(哔哩哔哩)在进入德州真人透视脚本软件靠谱后...
第1分钟方案!wepoker免... 第1分钟方案!wepoker免费脚本弱密码(透视)一贯存在有辅助神器(哔哩哔哩)小薇(辅助器软件下载...
第八分钟技法!智星德州插件最新... 第八分钟技法!智星德州插件最新版本更新内容详解(透视)真是是真的有辅助脚本(哔哩哔哩)1、这是跨平台...
第九分钟学习!epoker免费... 第九分钟学习!epoker免费透视脚本(透视)竟然真的有辅助脚本(哔哩哔哩)1、金币登录送、破产送、...
六分钟手筋!pokemmo免费... 六分钟手筋!pokemmo免费脚本(透视)确实是有辅助下载(哔哩哔哩)1、进入到pokemmo免费脚...
第二分钟举措!pokerrrr... 第二分钟举措!pokerrrr2辅助(透视)本来真的是有辅助脚本(哔哩哔哩)1、点击下载安装,pok...
第八分钟积累!wejoker辅... 第八分钟积累!wejoker辅助软件价格(透视)一贯真的有辅助安装(哔哩哔哩)wejoker辅助软件...