
This article was written in 2019. Versions, tools and recommendations may have changed since then. Newer posts are collected under .NET.
In .NET, there is a very fast and easy way to pump a variety of entities into an SQL database: SqlBulkCopy
1public void BulkInsert<TEntity>(string connectionString, string tableName, IList<TEntity> entities, params string[] columns)
2{
3 using SqlBulkCopy sqlCopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity | SqlBulkCopyOptions.KeepNulls)
4 using ObjectReader reader = ObjectReader.Create(entities, columns);
5 {
6 sqlCopy.DestinationTableName = tableName;
7 sqlCopy.WriteToServer(reader);
8 }
9}Usage:
1public class MyEntity
2{
3 public Id {get;set}
4 public Name {get;set;}
5 public EMail {get;set;}
6}
7
8public class MySqlExporter
9{
10 public void Export()
11 {
12 string connectionString = "your sql connection string";
13 string sqlTableName = "MyEntitiesTable";
14 List<MyEntity> myEntities = ... // here your code to read your existing entities or source
15
16 string[] copyParameters = {
17 nameof(MyEntity.Id)
18 nameof(MyEntity.Name),
19 nameof(MyEntity.EMail),
20 }
21
22 BulkInsert(connectionString, sqlTableName, myEntities, copyParameters);
23 }
24}Related articles

- 16 min read
Production Rate Limiting in ASP.NET Core
Most ASP.NET Core rate-limiting examples stop after registering a fixed window. That is enough to demonstrate the middleware, but it is not …

- 11 min read
The Big Decimal Bugfix with .NET 11
For more than two decades, (decimal)1.23 returned 1.23m. It looked correct, it passed every test and it was a polite lie.

- 10 min read
Distroless, Chiseled or Alpine: Choosing a .NET Base Image
Distroless, Chiseled and Alpine are often compared as three equivalent Linux distributions. They are not. Alpine is a distribution built …
Let's Work Together
Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.
