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辅助平台(透视)微乐家乡自建房辅助app(原来存在有辅助app)-哔哩哔...
透视中牌率!wepoker软件... 透视中牌率!wepoker软件辅助程序(透视)柚子联盟辅助器下载(一贯存在有辅助app)-哔哩哔哩亲...
透视辅助!佛手在线大菠萝辅助(... 透视辅助!佛手在线大菠萝辅助(透视)越乡游金花辅助(都是真的有辅助插件)-哔哩哔哩1、完成佛手在线大...
透视模拟器!hhpoker作必... 透视模拟器!hhpoker作必弊码(透视)呱呱丰城双剑辅助(确实真的是有辅助安装)-哔哩哔哩1、让任...
透视ai代打!大菠萝免费辅助(... 透视ai代打!大菠萝免费辅助(透视)欢聚水鱼智能辅助app(本来真的有辅助工具)-哔哩哔哩;1、全新...
据玩家消息!wepoker有没... 据玩家消息!wepoker有没有挂(透视)海南琼崖海南辅助功能(原来真的是有辅助工具)-哔哩哔哩1、...
透视教学!wepoker辅助透... 透视教学!wepoker辅助透视(透视)天天福建辅助器(确实真的有辅助安装)-哔哩哔哩1、天天福建辅...
透视安卓版!wepoker破解... 透视安卓版!wepoker破解是真的还是假的(透视)至友互娱情怀辅助插件(切实是有辅助下载)-哔哩哔...
透视透视!hhpoker破解工... 透视透视!hhpoker破解工具(透视)决战加血辅助(切实是真的辅助安装)-哔哩哔哩1)决战加血辅助...
透视智能ai!hhpoker外... 透视智能ai!hhpoker外开挂靠谱吗(透视)传送屋万能辅助器(本来有辅助下载)-哔哩哔哩1、很好...