GithubHelp home page GithubHelp logo

alecgn / mssql-helpers Goto Github PK

View Code? Open in Web Editor NEW
18.0 4.0 6.0 65 KB

MsSqlHelpers is a library to improve MS SQL Server common development tasks, like generating parametrized bulk inserts to be used with ADO.NET, Entity Framework and Dapper, and more.

License: MIT License

C# 100.00%
dapper entity framework ms sql server database ado bulk insert

mssql-helpers's Introduction

MsSqlHelpers

Build and tests status (mssql-helpers) Nuget version (mssql-helpers) Nuget downloads (MsSqlHelpers)

MsSqlHelpers is a library to improve MS SQL Server common development tasks, like generating parametrized bulk inserts to be used with ADO.NET, Entity Framework and Dapper, and more (in a near future).
To allow IDENTITY INSERT ON, there's an optional parameter in method call (default mode OFF).

ADO.NET usage:

using MsSqlHelpers;

...

var mapper = new MapperBuilder<Person>()
    .SetTableName("People") // could be ommited if your table's name is the same as you entity's class name
    .AddMapping(person => person.FirstName, columnName: "Name")
    .AddMapping(person => person.LastName, columnName: "Surename")
    .AddMapping(person => person.DateOfBirth) // in this case property's name is the same as table column's name
    .Build();
var people = new List<Person>()
{ 
    new Person() { FirstName = "John", LastName = "Lennon", DateOfBirth = new DateTime(1940, 10, 9) },
    new Person() { FirstName = "Paul", LastName = "McCartney", DateOfBirth = new DateTime(1942, 6, 18) },
};
var connectionString = "Server=SERVER_ADDRESS;Database=DATABASE_NAME;User Id=USERNAME;Password=PASSWORD;";
var sqlQueriesAndParameters = new MsSqlQueryGenerator().GenerateParametrizedBulkInserts(mapper, people);

using (var sqlConnection = new SqlConnection(connectionString))
{
    sqlConnection.Open();
    
    // Default batch size: 1000 rows or (2100-1) parameters per insert.
    foreach (var (SqlQuery, SqlParameters) in sqlQueriesAndParameters)
    {
        using (SqlCommand sqlCommand = new SqlCommand(SqlQuery, sqlConnection))
        {
            sqlCommand.Parameters.AddRange(SqlParameters.ToArray());
            sqlCommand.ExecuteNonQuery();
        }
    }
}

Entity Framework usage:

using MsSqlHelpers;

...

var mapper = new MapperBuilder<Person>()
    .SetTableName("People") // could be ommited if your table's name is the same as you entity's class name
    .AddMapping(person => person.FirstName, columnName: "Name")
    .AddMapping(person => person.LastName, columnName: "Surename")
    .AddMapping(person => person.DateOfBirth) // in this case property's name is the same as table column's name
    .Build();
var people = new List<Person>()
{ 
    new Person() { FirstName = "John", LastName = "Lennon", DateOfBirth = new DateTime(1940, 10, 9) },
    new Person() { FirstName = "Paul", LastName = "McCartney", DateOfBirth = new DateTime(1942, 6, 18) },
};
var sqlQueriesAndParameters = new MsSqlQueryGenerator().GenerateParametrizedBulkInserts(mapper, people);

// Default batch size: 1000 rows or (2100-1) parameters per insert.
foreach (var (SqlQuery, SqlParameters) in sqlQueriesAndParameters)
{
    _context.Database.ExecuteSqlRaw(SqlQuery, SqlParameters);
    // Depracated but still works: _context.Database.ExecuteSqlCommand(SqlQuery, SqlParameters);
}

Dapper usage:

using MsSqlHelpers;

...

var mapper = new MapperBuilder<Person>()
    .SetTableName("People") // could be ommited if your table's name is the same as you entity's class name
    .AddMapping(person => person.FirstName, columnName: "Name")
    .AddMapping(person => person.LastName, columnName: "Surename")
    .AddMapping(person => person.DateOfBirth) // in this case property's name is the same as table column's name
    .Build();
var people = new List<Person>()
{ 
    new Person() { FirstName = "John", LastName = "Lennon", DateOfBirth = new DateTime(1940, 10, 9) },
    new Person() { FirstName = "Paul", LastName = "McCartney", DateOfBirth = new DateTime(1942, 6, 18) },
};
var connectionString = "Server=SERVER_ADDRESS;Database=DATABASE_NAME;User Id=USERNAME;Password=PASSWORD;";
var sqlQueriesAndDapperParameters = new MsSqlQueryGenerator().GenerateDapperParametrizedBulkInserts(mapper, people);

using (var sqlConnection = new SqlConnection(connectionString))
{
    // Default batch size: 1000 rows or (2100-1) parameters per insert.
    foreach (var (SqlQuery, DapperDynamicParameters) in sqlQueriesAndDapperParameters)
    {
        sqlConnection.Execute(SqlQuery, DapperDynamicParameters);
    }
}

mssql-helpers's People

Contributors

alecgn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

mssql-helpers's Issues

Schema support

Great tool! Thank you
When specifying a table schema e.g.

.SetTableName("uccx.AgentStateDetail")

TableName later gets braces added and that caused my inserts to fail

I removed the [ and ] where they are at the moment and did this but there's no doubt some better way:

    private string _TableName;
    public string TableName {
        get { return _TableName; }
        set
        {
            if(value.StartsWith("[") || value.EndsWith("]") || value.Contains("."))
            {
                _TableName = value;
            }
            else
            {
                _TableName= "[" + value + "]";
            }
        } 
    }

As I didn't want to do the mappings by hand as my columns and properties were consistent I added this so that I didn't have to do any mapping. Wondered if it might be a helpful addition

    /// <summary>
    /// Use this method to auto map by column name
    /// </summary>
    /// <returns></returns>
    public MapperBuilder<T> AutoMapping()
    {
        foreach (PropertyInfo property in typeof(T).GetProperties())
        {
            _mapper.Mappings.Add(property.Name, property.Name);
        }

        return this;
    }

Thank you :-)

Identity Inserts

Thanks for the great tool!

Is there a way to set the identity insert to on and then off after the query is run?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.