0

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();

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.