Skip to content

C# Library to allow for a streamlined way of using Objects to bulk insert large amounts of data into a MSSQL or PostgreSQL database.

Notifications You must be signed in to change notification settings

gbachs/SqlBulkInsert.Helper

Repository files navigation

SqlBulkInsert.Helper

Build Status Build Status

Example of inserting a list of objects

public class BulkInsertExample
{
	public void BulkInsertUsers()
	{
		var users = GetUsers().ToList();
		var sqlWriter = new SqlWriter<User>();

		using (var connection = new SqlConnection("<ConnectionString>"))
		{
			connection.Open();
			using (var transaction = connection.BeginTransaction())
			{
				sqlWriter.Write(transaction, users);
			}
		}
	}

	private static IEnumerable<User> GetUsers()
	{
		for (var i = 0; i < 100000; i++)
		{
			yield return new User
			{
				FirstName = Guid.NewGuid().ToString(),
				LastName = Guid.NewGuid().ToString(),
				Id = Guid.NewGuid(),
				UserName = Guid.NewGuid().ToString()
			};
		}
	}

	[Table("Users")]
	private class User
	{
		[Column("UserName")]
		public string UserName { get; set; }

		[Column("FirstName")]
		public string FirstName { get; set; }

		[Column("LastName")]
		public string LastName { get; set; }

		[Column("Id")]
		public Guid Id { get; set; }
	}
}

Example of inserting a list of objects when one of the properties of the object is auto generated from an identity column in the sql table. This is denoted by using the GeneratedColumn attribute on the property that is associated to the sql identity column. When the data is inserted the SqlWriter will then update the objects with the new values from the identity column.

public class BulkInsertExample
{
	public void BulkInsertUsers()
	{
		var users = GetUsers().ToList();
		var sqlWriter = new SqlWriter<User>();

		using (var connection = new SqlConnection("<ConnectionString>"))
		{
			connection.Open();
			sqlWriter.Write(transaction, users);
		}
	}

	private static IEnumerable<User> GetUsers()
	{
		for (var i = 0; i < 100000; i++)
		{
			yield return new User
			{
				FirstName = Guid.NewGuid().ToString(),
				LastName = Guid.NewGuid().ToString(),
				UserName = Guid.NewGuid().ToString()
			};
		}
	}

	[Table("Users")]
	private class User
	{
		[Column("UserName")]
		public string UserName { get; set; }

		[Column("FirstName")]
		public string FirstName { get; set; }

		[Column("LastName")]
		public string LastName { get; set; }

		[GeneratedColumn("Id")]
		public Guid Id { get; set; }
	}
}

About

C# Library to allow for a streamlined way of using Objects to bulk insert large amounts of data into a MSSQL or PostgreSQL database.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages