Entity Framework Core Insert multiple entities similar to SQL single insert statement

entity-framework-core performance

Question

How do you manage to get the same effect as SQL simple

INSERT INTO myTable VALUES (X), (Y), (Z),..... 

and so on?

1
2
7/28/2019 6:41:55 PM

Accepted Answer

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

2
7/28/2019 10:45:28 AM

Popular Answer

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 DbContextis 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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow