0

I have a pretty simple ActionResult function that is called from my view and it receives a number from it, I want to add this much new rows in my database equals to that number and the only column I fill in is the id of the formation it is related to, here is my code as of now

public ActionResult AddInfo(int? idfrm,int? NumberToAdd)
    {
        using (InscriptionFormationEntities dbm = new InscriptionFormationEntities())
        {
            for(int i=0;i<NumberToAdd;i++)
            {
                INSC_MoreInfo NewEntry= new INSC_MoreInfo ();
                NewEntry.idformation = idfrm;
                dbm.INSC_MoreInfo .Add(info);
            }
            dbm.SaveChanges();
        }
            return View(idfrm);
    }

The code above works perfectly but I was wondering if there was a way to arrive at the same result without relying on a for loop since it could be slow if for example the number of new entry to make is really big ( it could very well be in this case)

**Note:**My project is made in asp.net mvc 5,my code is database first and I use Entity framework to connect with it

4
  • Why would it be slow? It is find to do what you are doing. Commented Jul 14, 2017 at 18:32
  • @CodingYoshi Because If I have to add 1000000 new entry my loop is gonna create a new instance plus add it each time Commented Jul 14, 2017 at 18:34
  • You can replace the for loop with AddRange call, but I don't think it's relevant, since the slowest part is inserting the records to the database (when you call SaveChanges) since EF does not support bulk insert. Commented Jul 14, 2017 at 18:35
  • @IvanStoev yeah I tried to have a bulk insert but it seems that entity-framework dosen't support it natively Commented Jul 14, 2017 at 18:36

1 Answer 1

3

The short answer is no - you can't eliminate iterating to create X number of items. You could rewrite your code to technically eliminate the for loop, but behind the scenes you still have to use an iterator of some sort to create the objects.

As long as you are only calling SaveChanges() once outside the loop, you shouldn't see any significant performance issues with this approach. Even though you use a for loop, this ultimately results in one SQL Insert statement which will create all records in a single trip to the database (technically may be 2 trips to get versions and things, but one for the query).

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

2 Comments

Ok thanks for the info, so this is the best way to do it I guess then ?
Yes, basically what you have is the best way

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.