none
How to save changes of courses in EmployeeCourse table RRS feed

  • Question

  • What i Need

    I need to save changes in courses in EmployeeCourse table

    by remove all course for employee from EmployeeCourse table

    then add courses after changes

    Problem

    when add changes in courses after remove i get error in save changes() function

    {"An error occurred while updating the entries.

    The INSERT statement conflicted with the FOREIGN KEY constraint

    \"FK_EmployeeCourse_Course\". The conflict occurred in database \"mycourse\",

    table \"dbo.Course\", column 'Id'.\r\nThe statement has been terminated."}

    under submit button edit [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();
    }
    Debug result


    debug add as image below

    add courses error

    Details

    Relation between two tables one to many

    EmployeeCourse

    Id(primary key) CourseId(forign key) EmployeeId(forign key)

    Course table in database

    Id(pk) CourseName

    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>


    to retrieve courses from database in edit view i used code below

    <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>
    
    model used for that as following
     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; }
        }
    }
    Notice 461 value not found in table Course in database
    Sunday, September 25, 2016 2:21 PM

Answers

  • Hi eng-ahmed-salah,

    Please check if your table named EmployeeCourse's field named Id has a identity property. if it does not have related property, please add related property, like this:

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Monday, September 26, 2016 5:56 AM
    Moderator

All replies

  • I need to save changes in courses in EmployeeCourse table

    by remove all course for employee from EmployeeCourse table

    then add courses after changes

    What kind of nonsense is this? Why can't you update existing records and insert new ones into the collection and do the save without doing a total delete of everything and putting it back?

    Sunday, September 25, 2016 9:10 PM
  • Hi eng-ahmed-salah,

    Please check if your table named EmployeeCourse's field named Id has a identity property. if it does not have related property, please add related property, like this:

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Monday, September 26, 2016 5:56 AM
    Moderator