1

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();
        }
7
  • 1
    try putting Student objStu = new Student(); inside the loop. Commented Jul 8, 2014 at 17:40
  • You don't get any updates with the loop or you only get one update with the loop? Commented Jul 8, 2014 at 17:41
  • I don't get any update @MikeCheel Commented Jul 8, 2014 at 17:44
  • I would think your original code would first add a student to the database and then the second time through the loop it would update the first record it put in. Is that not happening? Commented Jul 8, 2014 at 17:45
  • no its not happening @MikeCheel Commented Jul 8, 2014 at 17:46

1 Answer 1

6

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is because when you add the objStu object to the context, it is "tracked". Any future changes to this object will be persisted with db.SaveChanges() is called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.