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

相关内容

热门资讯

科普透视!hhpoker是真的... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家在这款游戏中打...
教你透视!aapoker脚本,... 教你透视!aapoker脚本,aapoker透视插件,竟然有辅助插件(哔哩哔哩)1、完成有辅助插件,...
曝光透视!wejoker辅助机... 曝光透视!wejoker辅助机器人,wepoker辅助插件功能,本来是真的有辅助插件(哔哩哔哩)1、...
透视透视!wepoker模拟器... 透视透视!wepoker模拟器哪个好用,wepoker透视苹果系统,一贯有辅助工具(哔哩哔哩)epo...
分享透视!wepoker私人局... 分享透视!wepoker私人局透视教程,wepoker有什么规律,真是真的是有辅助技巧(哔哩哔哩)1...
关于透视!hhpoker是真的... 关于透视!hhpoker是真的还是假的,hhpoker开挂教程,真是真的有辅助插件(哔哩哔哩)1、让...
推荐透视!德普之星的辅助工具介... 推荐透视!德普之星的辅助工具介绍,德普软件,真是一直总是有辅助攻略(哔哩哔哩)1、上手简单,内置详细...
推荐透视!wepoker私人局... 推荐透视!wepoker私人局透视方法,wepoker如何设置透视,都是真的是有辅助软件(哔哩哔哩)...
有挂透视!aapoker辅助插... 有挂透视!aapoker辅助插件工具,aapoker怎么提高中牌率,确实存在有辅助教程(哔哩哔哩)1...
普及透视!hhpoker怎么防... 普及透视!hhpoker怎么防作比弊,hhpoker辅助挂是真的吗,都是存在有辅助软件(哔哩哔哩)透...