How do you manage to get the same effect as SQL simple
INSERT INTO myTable VALUES (X), (Y), (Z),.....
and so on?
Join Stack Overflow to learn, share knowledge, and build your career.
How do you manage to get the same effect as SQL simple
INSERT INTO myTable VALUES (X), (Y), (Z),.....
and so on?
You may generate the query and execute the same as per the following;
DatabaseContext.Database.ExecuteSqlCommand(yourQuery);
Refer documentation here. Even though it is relevant to EF, it is applicable to EF Core as well
If you are using EF Core with SQL Server and has to insert a lot of entities then you can pick one of the following libs that are using SqlBulkCopy:
The usage is very easy
List<MyEntity> entities = ...;
await context.BulkInsertAsync(entities);
SqlBulkCopy is the fastest way to get the entities into a SQL Server.
Please note, as with raw SQL statements the
DbContext
is not aware of this operations, so some caution is required. But, if you have to insert a lot of data then there is not much choice as to use some techniques that are closer to the database.
var entityList = new List<Entity>();
entityList = {
new Entity { Property1 = Value, Property2 = "Value"},
new Entity { Property1 = Value, Property2 = "Value"}
}
context.AddRange(entityList); //Add() for single entity
context.SaveChanges();
SaveChanges()
of course - at the AddRanges()
DetectChanges will be called only once.
– FlixRo
Jul 28 '19 at 10:57