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

相关内容

热门资讯

第2分钟课程!pokermas... 第2分钟课程!pokermaster脚本(透视)其实真的有辅助辅助(哔哩哔哩)1、让任何用户在无需p...
第8分钟步骤!wepoker作... 第8分钟步骤!wepoker作必弊方法(透视)好像存在有辅助教程(哔哩哔哩)小薇(辅助器软件下载)致...
第四分钟大纲!hhpoker免... 第四分钟大纲!hhpoker免费辅助器(透视)总是真的是有辅助教程(哔哩哔哩)进入游戏-大厅左侧-新...
第一分钟妙计!wepoker数... 第一分钟妙计!wepoker数据分析(透视)原来有辅助插件(哔哩哔哩)1、第一分钟妙计!wepoke...
1分钟方案!wepoker可以... 1分钟方案!wepoker可以开透视吗(透视)竟然存在有辅助下载(哔哩哔哩)1、1分钟方案!wepo...
两分钟步骤!hhpoker有辅... 两分钟步骤!hhpoker有辅助吗(透视)一直存在有辅助安装(哔哩哔哩)1、用户打开应用后不用登录就...
第九分钟窍门!wepoker辅... 第九分钟窍门!wepoker辅助软件价格(透视)都是存在有辅助辅助(哔哩哔哩)1、玩家可以在wepo...
第七分钟手册!德州透视hhpo... 第七分钟手册!德州透视hhpoker(透视)本来是真的有辅助插件(哔哩哔哩)1、用户打开应用后不用登...
六分钟攻略!wepoker代打... 六分钟攻略!wepoker代打辅助(透视)本来是有辅助辅助(哔哩哔哩)1、wepoker代打辅助辅助...
五分钟办法!wepoker怎么... 五分钟办法!wepoker怎么获得好牌(透视)确实真的有辅助下载(哔哩哔哩)一、wepoker怎么获...