【问题标题】:How to save changes of courses in EmployeeCourse table如何在 EmployeeCourse 表中保存课程的更改
【发布时间】:2016-09-25 00:58:08
【问题描述】:

我需要什么

我需要在 EmployeeCourse 表中保存课程更改

通过从 EmployeeCourse 表中删除员工的所有课程

然后在更改后添加课程

问题

删除后在课程中添加更改时,我在保存更改()函数中出现错误

{"更新条目时出错。

INSERT 语句与 FOREIGN KEY 约束冲突

\"FK_EmployeeCourse_Course\"。数据库\"mycourse\"中发生冲突,

表\"dbo.Course\",列'Id'。\r\n语句已终止。"}

在提交按钮下编辑[httppost]

public ActionResult Edit(EditEmployeeVm model)
        {
var emp = db.Employees.FirstOrDefault(f => f.Id == model.Id);
// remove all courses
                foreach (EmployeeCourse eec in emp.EmployeeCourses.ToList())
                {
                    var ec = db.EmployeeCourses.Find(eec.Id);
                    db.EmployeeCourses.Remove(ec);
                }
// add courses again
                foreach (var couseid in model.CourseIds)
                {
                    db.EmployeeCourses.Add(new EmployeeCourse { CourseId = couseid, EmployeeId = emp.Id });

                }
                db.SaveChanges();
}

调试结果

调试添加如下图

详情

两个表之间的一对多关系

员工课程

Id(主键) CourseId(外键) EmployeeId(外键)

数据库中的课程表

Id(pk) 课程名称

I using following view model for edit to get CourseIds 

@model StudentCourses.Models.EditEmployeeVm

    $(function () {
        $(document).on("click", ".remove", function (e) {
            e.preventDefault();
            $(this).closest(".course-item").remove();

        });
        $('#AvailableCourses').change(function () {
            var val = $(this).val();
            var text = $("#AvailableCourses option:selected").text();
            var existingCourses = $("input[name='CourseIds']")
                .map(function () { return this.value; }).get();

            if (existingCourses.indexOf(val) === -1) {

                var newItem = $("<div/>").addClass("course-item")
          .append(text + ' <a href="#" class="remove" data-id="' + val + '">Remove </a>');
                newItem.append('<input type="text" name="CourseIds" value="' + val + '" />');

                $("#items").append(newItem);
            }
        });
    });
</script>

为了在编辑视图中从数据库中检索课程,我使用了下面的代码

<div>
    @using (Html.BeginForm())
    {

        @Html.HiddenFor(g => g.Id)
        @Html.LabelFor(f => f.Name)
        @Html.DropDownList("AvailableCourses", Model.Courses, "Select")
        <h4>Existing courses</h4>
        <div id="items"></div>
        foreach (var c in Model.ExistingCourses)
        {
            <div class="course-item">
                @c.Name <a href="#" class="remove" data-id="@c.Id">Remove </a>
                <input type="text" name="CourseIds" value="@c.Id" />
            </div>
        }

    }
</div>

用于此的模型如下

    public class EditEmployeeVm
    {
        public int Id { set; get; }
        public List<SelectListItem> Courses { get; set; }
        public int[] CourseIds { set; get; }
        public List<CourseVm> ExistingCourses { set; get; }
    }
    public class CourseVm
    {
        public int Id { set; get; }
        public string Name { set; get; }
    }
}

更新

public ActionResult Edit(int id)
        {
            var vm = new EditEmployeeVm { Id = id };
            var emp = db.Employees.FirstOrDefault(f => f.Id == id);
            vm.Name = emp.Name;
            vm.ExistingCourses = db.EmployeeCourses
                                    .Where(g => g.EmployeeId == id)
                                    .Select(f => new CourseVm
                                    {
                                        Id = f.Id,
                                        Name = f.Course.CourseName
                                    }).ToList();
            vm.CourseIds = vm.ExistingCourses.Select(g => g.Id).ToArray();
            vm.Courses = db.Courses.Select(f => new SelectListItem
            {
                Value = f.Id.ToString(),
                Text = f.CourseName
            }).ToList();

            return View(vm);
        }

【问题讨论】:

  • 461 是Course 表中的有效 courseId 吗?
  • 对不起,我混淆了 461 在课程表中无效
  • 课程表有两个值 1 python 2 delphi
  • 谁能帮帮我
  • 所以您从表单中发送了错误的值。您可能需要修复获得值 461 的位置。确保您从课程表中获取 Id。

标签: asp.net-mvc linq-to-sql linq-to-entities entity-framework-5


【解决方案1】:

在您的 EDIT Get 操作中,您为 CourseVm 使用了错误的 ID。它应该是课程 ID,但您正在设置 EmployeeCourse 记录/实体 ID。

这应该可以解决它。

vm.ExistingCourses = db.EmployeeCourses.Where(g => g.EmployeeId == id)
                                       .Select(f => new CourseVm
                                           {
                                              Id = f.Course.Id,
                                              Name = f.Course.CourseName
                                           }).ToList();

【讨论】:

  • 非常感谢它已解决,但如果可能,在删除所有课程时剩余一点未解决,然后单击提交给我异常错误对象引用未设置为对象的实例。在这一行 foreach (var couseid in model.CourseIds)
猜你喜欢
  • 1970-01-01
  • 2020-06-07
  • 2015-07-03
  • 2014-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-05
  • 1970-01-01
相关资源
最近更新 更多