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

相关内容

热门资讯

透视游戏"wepok... 透视游戏"wepoker有辅助功能吗"详细辅助AA德州教程(透视脚本神器);科技安装教程;13670...
透视新版"pokem... 透视新版"pokemmo手机脚本辅助器"详细辅助透牌教程(购买模拟器软件)是一款可以让一直输的玩家,...
透视规律"hhpok... 透视规律"hhpoker有没有作弊辅助"详细辅助教你攻略(私局代打软件);科技安装教程;136704...
透视脚本"hhpok... 透视脚本"hhpoker万能辅助器"详细辅助透明教程(破解工具辅助)1、玩家可以在hhpoker万能...
透视科技"德州局透视... 您好,德州局透视这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在这款游...
透视攻略"hhpok... 透视攻略"hhpoker怎么防作弊"详细辅助专业教程(辅助器免费辅助);亲真的是有正版授权,小编(透...
透视游戏"福建大菠萝... 此外,数据分析德州(福建大菠萝万能辅助器)辅助神器app还具备辅助透视行为开挂功能,通过对客户福建大...
透视ai代打"智星德... 透视ai代打"智星德州辅助译码插件靠谱吗"详细辅助必备教程(-h5下载方法);支持多人共享记分板与复...
透视辅助"佛手在线大... 透视辅助"佛手在线大菠萝辅助"详细辅助新2025版(的辅助器方法)1、很好的工具软件,可以解锁游戏的...
透视私人局"wepo... 透视私人局"wepokerplus作弊"详细辅助必赢方法(底牌透视透明);人气非常高,ai更新快且高...