ASP.NETCoreMVC:在发布Edit方法之前删除多对多条目。
创始人
2024-09-18 00:01:13
0

在多对多关联表上执行标准SQL语句,以在编辑方法中删除多对多关联条目。可以通过使用DbContext来执行SQL语句。

以下是示例代码:

public async Task Edit(int id, StudentViewModel model)
{
    if (ModelState.IsValid)
    {
        var student = await _context.Students
            .Include(s => s.StudentCourses)
            .SingleOrDefaultAsync(s => s.Id == id);

        if (student != null)
        {
            //delete all existing student courses
            var deleteSql = $"DELETE FROM StudentCourses WHERE StudentId = '{id}'";
            await _context.Database.ExecuteSqlCommandAsync(deleteSql);

            //update student properties
            student.Name = model.Name;
            student.Age = model.Age;

            //add newly selected student courses
            foreach (var courseId in model.SelectedCourseIds)
            {
                var studentCourse = new StudentCourse
                {
                    StudentId = id,
                    CourseId = courseId
                };

                _context.Add(studentCourse);
            }

            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
    }

    return View(model);
}

相关内容

热门资讯

带你了解!aapoker透视脚... 带你了解!aapoker透视脚本,微扑克辅助下载,都是是有挂(有人有挂)1、上手简单,内置详细流程视...
玩家必备科技!hhpoker智... 玩家必备科技!hhpoker智能辅助插件,hhpoker免费透视脚本,确实有挂(确实有挂)1)辅助插...
玩家必看教程!aa poker... 玩家必看教程!aa poker辅助,aapoker透视插件,一贯有挂(有挂技巧)1、下载好正确养号方...
我来分享!wepoker透视脚... 我来分享!wepoker透视脚本是什么,hhpoker辅助软件是真的么,本来真的有挂(存在有挂)1、...
重大通报!德普辅助器怎么用,h... 重大通报!德普辅助器怎么用,hhpkoer辅助挂是真的吗,一直是真的有挂(有挂辅助)1、脚本辅助下载...
研究成果!wpk辅助,soho... 研究成果!wpk辅助,sohoo poker辅助器,竟然真的有挂(有挂总结)1、破解器简单,机器人操...
三分钟了解!德普之星辅助软件,... 三分钟了解!德普之星辅助软件,德州透视插件,确实真的有挂(的确有挂)进入游戏-大厅左侧-新手福利-激...
必备科技!wepoker私人局... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款游戏中打...
推荐几款新版!aapoker真... 推荐几款新版!aapoker真的假的,wepoker养号规律,果然是真的有挂(有挂详情)1、脚本辅助...
推荐一款!werplan怎么作... 推荐一款!werplan怎么作弊,cloudpoker外挂,竟然有挂(有挂方式)亲,关键说明,透视脚...