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

Answers


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.


Need Your Help

How to draw a Polygon with X sides (all equal length & angles)

java math polygon

I am looking to calculate the X and Y points of each point on a polygon, given the number of sides, and the fact that all sides are equal. I would also have the width and height constraints of the

Parse Push Notifications, how do I modify a variable in the current view controller when a notification is recieved?

ios xcode uiviewcontroller parse.com

when my app receives a push notification I want to increment a variable i.e. totalMessages++. I know that :

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.