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

相关内容

热门资讯

必看攻略!pokemmo手机版... 必看攻略!pokemmo手机版脚本(辅助挂)原来是真的有挂(有挂详情)1、必看攻略!pokemmo手...
记者发布!wepoker私人局... 记者发布!wepoker私人局透视方法(辅助挂)真是有挂(讲解有挂)1、金币登录送、破产送、升级送、...
教程辅助!hhpoker德州有... 教程辅助!hhpoker德州有挂吗(辅助挂)其实是有挂(有挂方法)1、这是跨平台的hhpoker德州...
六分钟了解!德普之星辅助软件(... 六分钟了解!德普之星辅助软件(辅助挂)真是是有挂(有挂透视)1、进入游戏-大厅左侧-新手福利-激活码...
详细说明!aapoker辅助工... 详细说明!aapoker辅助工具安全吗(辅助挂)一贯真的有挂(有挂猫腻)aapoker辅助工具安全吗...
总算了解!aapoker插件(... 总算了解!aapoker插件(辅助挂)本来是真的有挂(有挂秘诀)1、下载好aapoker插件正确养号...
重磅来袭!pokermaste... 重磅来袭!pokermaster修改器(辅助挂)真是存在有挂(有挂讲解)1、pokermaster修...
六分钟了解!拱趴大菠萝万能挂图... 六分钟了解!拱趴大菠萝万能挂图解(辅助挂)竟然存在有挂(揭秘有挂)暗藏猫腻,小编详细说明拱趴大菠萝万...
总算明白!wpk私人辅助(辅助... 总算明白!wpk私人辅助(辅助挂)一直是真的有挂(有挂辅助)1、下载好wpk私人辅助正确养号方法之后...
玩家必看科普!aapoker真... 玩家必看科普!aapoker真的假的(辅助挂)切实真的是有挂(有挂技巧)1、完成aapoker真的假...