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

相关内容

热门资讯

1.9分钟了解!约局吧透视挂下... 1.9分钟了解!约局吧透视挂下载,约局吧德州有挂吗,第三方教程(有挂方法)1、许多玩家不知道约局吧透...
玩家实测!哈糖大菠萝攻略,hh... 玩家实测!哈糖大菠萝攻略,hhpkoer辅助器视频,安装教程(有挂方法);致您一封信;亲爱hhpko...
一分钟了解!wepoker安装... 一分钟了解!wepoker安装教程,wepoker轻量版书签,黑科技教程(有挂方法);wepoker...
玩家实测!hhpoker有作弊... 玩家实测!hhpoker有作弊的吗,wepoker透视底牌脚本,普及教程(有挂透视);原来确实真的有...
重大通报!wepokerplu... 这是一款非常优秀的菠萝辅助器免费版的功能介绍 ia辅助检测软件,能够让你了解到菠萝辅助器免费版的功能...
一分钟了解!hhpoker怎么... 一分钟了解!hhpoker怎么防作弊,wepoker国外版透视,揭秘教程(有挂教程);hhpoker...
重大通报!wepoker底牌透... 重大通报!wepoker底牌透视,wepoker俱乐部辅助,透牌教程(有挂技巧);玩家必备必赢加哟《...
玩家必备科普!wepoker俱... 玩家必备科普!wepoker俱乐部辅助,aapoker破解侠是真的吗,AI教程(有挂神器)这是由厦门...
重大通报!wpk私人辅助,po... 重大通报!wpk私人辅助,pokemmo脚本辅助器下载,2025新版总结(有挂技巧)是一款可以让一直...
避坑细节!wepokerplu... 避坑细节!wepokerplus开挂,wpk安卓下载辅助,黑科技教程(有挂辅助)1、玩家可以在wpk...