0

see my code how i am adding multiple data in db.

List<Employee> oEmp = new List<Employee>
{
    new Employee{Name="New employee2", Salary=5000},
    new Employee{Name="New employee3", Salary=6000},
    new Employee{Name="New employee4", Salary=7000}
};

using (var ctx = new TestEFContext())
{
    foreach (Employee emp in oEmp)
    {
        ctx.Employees.Add(emp);
    }
    ctx.SaveChanges();
}

just curious to know how EF6 insert multiple data? does it insert multiple data into db in one go or add data one by one internally?

does the above code can be consider as bulk insert or bulk insert is fully different?

i saw people use many different extension to do bulk insert with EF. here are one link https://stackoverflow.com/a/43979807/6188148

so i have two questions in this post. please answer two question in details.

1) HOW EF insert mutiple data in db.....in one go or something different happen behind the curtain?

2) the way i am inserting multiple data in table....will it be consider bulk insert or bulk insert is different one?

thanks

Monojit Sarkar
  • 2,353
  • 8
  • 43
  • 94

1 Answers1

0

Disclaimer: I'm the owner of the project Entity Framework Extensions

HOW EF insert mutiple data in db.....in one go or something different happen behind the curtain?

EF perform a database round-trip for every entity you insert.

So if you insert 5000 entities, 5000 database round-trip will be performed.

It's always the same strategy used no matter the number of entities used.

the way i am inserting multiple data in table....will it be consider bulk insert or bulk insert is different one?

Bulk Insert library is completely different. They read the model and use SqlBulkCopy under the hood to perform Bulk Insert.

Your code will make a database round-trip for every entity which is INSANELY slow when thousands of entities are involved.

Should I use AddRange instead of Add?

Yes, when adding multiple entities, AddRange will only detect change once which dramatically improve the performance to add entities in the context.

Jonathan Magnan
  • 10,874
  • 2
  • 38
  • 60