ksg
ksg

Reputation: 4067

Why only the last item is inserted into database when adding multiple items?

I am trying to add multiple child records into the database,but only the last item gets inserted into the database.

Model

public string[] CourseID { get; set; }
public SelectList CourseList { get; set; }

Controller

StudentWalkInn _studentWalkInn = new StudentWalkInn();
....
....
//CourseId is of type string[]
if (mdlWalkInn.CourseID.Length > 0)
{
   StudentWalkInnCourse _studentCourse = new StudentWalkInnCourse();
   foreach (var courseId in mdlWalkInn.CourseID)
   {
       _studentCourse.CourseID=Convert.ToInt32(courseId);
       _studentWalkInn.StudentWalkInnCourses.Add(_studentCourse);
   }
}

_db.StudentWalkInns.Add(_studentWalkInn);
int i = _db.SaveChanges();
if (i > 0)
{
       //success message
}

Upvotes: 2

Views: 81

Answers (3)

Yacoub Massad
Yacoub Massad

Reputation: 27871

You are using the same StudentWalkInnCourse object. Even if you add it multiple times, EF will detect that it is the same object and will not add a new entity.

Move the following line inside the loop.

StudentWalkInnCourse _studentCourse = new StudentWalkInnCourse();

Here is how the loop would look like:

foreach (var courseId in mdlWalkInn.CourseID)
{
    StudentWalkInnCourse _studentCourse = new StudentWalkInnCourse();
    _studentCourse.CourseID=Convert.ToInt32(courseId);
    _studentWalkInn.StudentWalkInnCourses.Add(_studentCourse);
}

Upvotes: 2

BendEg
BendEg

Reputation: 21108

You need to create the new instance in the loop, because only setting a new id does not work.

if (mdlWalkInn.CourseID.Length > 0)
{
   foreach (var courseId in mdlWalkInn.CourseID)
   {
        StudentWalkInnCourse _studentCourse = new StudentWalkInnCourse();
       _studentCourse.CourseID=Convert.ToInt32(courseId);
       _studentWalkInn.StudentWalkInnCourses.Add(_studentCourse);
   }
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

The reason why only the last item is added is that you keep adding the same instance. When you change the ID in the loop, LINQ2SQL interprets it as a change of ID, not as an addition of a new item.

Adding different instances in each iteration of the loop should fix this problem:

foreach (var courseId in mdlWalkInn.CourseID)
{
    var _studentCourse = new StudentWalkInnCourse {
        CourseID = Convert.ToInt32(courseId)
    };
    _studentWalkInn.StudentWalkInnCourses.Add(_studentCourse);
}

Upvotes: 3

Related Questions