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

相关内容

热门资讯

透视揭幕"we-po... 透视揭幕"we-poker软件"切实有辅助挂(哔哩哔哩)1、点击下载安装,we-poker软件脚本分...
透视专业"wepok... 透视专业"wepoker有辅助吗"好像真的是有辅助教程(哔哩哔哩)1、点击下载安装,wepoker有...
透视详情"wepok... 透视详情"wepoker可以开透视吗"其实是真的辅助脚本(哔哩哔哩)1、操作简单,无需wepoker...
透视分享"wepok... 透视分享"wepoker是不是有人用挂"总是存在有辅助软件(哔哩哔哩)1、点击下载安装,wepoke...
透视详细"购买的wp... 透视详细"购买的wpk辅助在哪里下载"一贯真的有辅助工具(哔哩哔哩)1、超多福利:超高返利,海量正版...
透视普及"wepok... 透视普及"wepoker透视版下载"好像存在有辅助软件(哔哩哔哩)1、实时wepoker透视版下载透...
透视揭露"pokem... 透视揭露"pokemmo脚本最新版"其实是真的辅助软件(哔哩哔哩)小薇(辅助器软件下载)致您一封信;...
透视开挂"poker... 透视开挂"poker world辅助"本来是真的辅助插件(哔哩哔哩)在进入poker world辅助...
透视解谜"wpk安卓... 透视解谜"wpk安卓下载辅助"切实真的是有辅助攻略(哔哩哔哩)1)wpk安卓下载辅助免费钻石:进一步...
透视详细"wepok... 透视详细"wepoker有辅助工具吗"一直有辅助教程(哔哩哔哩)1、用户打开应用后不用登录就可以直接...