user3461957
user3461957

Reputation: 163

DbContext object not working from within loop

Here is my ActionMethod, it does not populate data to database.

private StudentDBContext db = new StudentDBContext();

public ActionResult PopulateData()
        {
            Student objStu = new Student();

            for(int i=0;i<2;i++)
            {
                objStu.ID = i+1;
                objStu.name = "something";
                db.Students.Add(objStu);
                db.SaveChanges();
            }


            return View();
        }

Only time when it does is when I use it without loop(as shown below) why is that so?

public ActionResult PopulateData()
        {
            Student objStu = new Student();

            //for(int i=0;i<2;i++)
            //{
                objStu.ID = 1;
                objStu.name = "something";
                db.Students.Add(objStu);
                db.SaveChanges();
            //}


            return View();
        }

Upvotes: 1

Views: 890

Answers (1)

Eric Scherrer
Eric Scherrer

Reputation: 3388

You are adding the same student over and over again. Instead, create the new student (objStu) inside the loop:

public ActionResult PopulateData()
{        
    for(int i=0;i<2;i++)
    {
        Student objStu = new Student();
        objStu.ID = i+1;
        objStu.name = "something";
        db.Students.Add(objStu);
    }

    db.SaveChanges();

    return View();
}

Upvotes: 6

Related Questions