Nate Pet
Nate Pet

Reputation: 46222

MVC AddObject Create multiple records

I have a list which contains multiple records. I like to use the AddObject to create those records but what is happening is that it creates just the last record in the list.

Here is the code

    foreach (var item in invlist) {

         invmodel.tblrec.FirstName = item.FirstName;
         invmodel.tblrec.LastName = item.LastName;

         db.tblRec.AddObject(invmodel.tblrec);                         

     }

     db.SaveChanges();

Upvotes: 0

Views: 1199

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

I would start with this very simple modification of your code:

foreach (var item in invlist) {

     var tblRec = new TblRec(); 
     tblRec.FirstName = item.FirstName;
     tblRec.LastName = item.LastName;

     db.tblRec.AddObject(tblRec);                         

 }

 db.SaveChanges();

Why? Because your code is repeatedly adding the same instance and for EF it is still the same object - it will either result in exception or only the last item will be inserted to database.

Upvotes: 2

Related Questions