0

How to insert same record in multiple times without using for loop because its taking to much time I want to insert 10lack record at a time

              for (int i = 0; i < 1000; i++)
            {
                List<student> students = new List<student>
                 {
                   new Student{student_id = i,Name= "new"}
                 };
                db.Set<Student>().AddRange(students);
                db.SaveChanges();
            }

This above code taking to much time to inserting 10lack record.is it possible to insert same Name with different student_id multiple times without using for loop?

3
  • 1
    Student_id is different according to your code then, how you are saying you are inserting the same record ?? Commented Apr 18, 2019 at 7:23
  • yes u'r right but I need same name with different student_id is it possible without using for loop? Commented Apr 18, 2019 at 7:37
  • 1
    then according to me the loop is only the option.., you can improve your code by using SaveChanges() outside the loop area and declare the List<Student> before the loop. using this approach you can improve the performance of your code. Commented Apr 18, 2019 at 7:42

2 Answers 2

1

Did you try calling SaveChanges() after the loop? Also I recommend making the student ID an auto generated key and adding each student with an add directly to the set instead of an addrange with a list.

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

Comments

0

You need to move db code out of the loop:

//Declare the list object here
List<Student> students = new List<Student>();

for (int i = 0; i < 1000; i++)
{
    students.Add(new Student{student_id = i,Name= "new"});
}

db.Set<Student>().AddRange(students);
db.SaveChanges(); //Save changes to DB

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.