├── .github └── workflows │ ├── build-and-test.yml │ └── build-test-and-deploy.yml ├── .gitignore ├── LICENSE ├── README.md └── src ├── MsSqlHelpers.Tests ├── MsSqlHelpers.Tests.csproj ├── MsSqlQueryGeneratorTests.cs └── Person.cs ├── MsSqlHelpers.sln └── MsSqlHelpers ├── Enums └── MsSqlUserLanguage.cs ├── Extensions └── Extensions.cs ├── Icon └── mssql-helpers-icon.png ├── Interfaces └── IMsSqlQueryGenerator.cs ├── Mapper.cs ├── MapperBuilder.cs ├── MsSqlHelpers.csproj └── MsSqlQueryGenerator.cs /.github/workflows/build-and-test.yml: -------------------------------------------------------------------------------- 1 | name: build-and-test 2 | on: 3 | push: 4 | branches: 5 | - develop 6 | jobs: 7 | build-and-test: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v2 11 | 12 | - name: Setup .NET Core 13 | uses: actions/setup-dotnet@v1 14 | with: 15 | dotnet-version: '3.1.x' 16 | 17 | - name: Build 18 | run: dotnet build --configuration Release src/MsSqlHelpers/MsSqlHelpers.csproj 19 | 20 | - name: Run tests 21 | run: dotnet test src/MsSqlHelpers.Tests/MsSqlHelpers.Tests.csproj 22 | -------------------------------------------------------------------------------- /.github/workflows/build-test-and-deploy.yml: -------------------------------------------------------------------------------- 1 | name: build-test-and-deploy 2 | on: 3 | push: 4 | branches: 5 | - main 6 | jobs: 7 | build-test-and-deploy: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v2 11 | 12 | - name: Build 13 | run: dotnet build --configuration Release src/MsSqlHelpers/MsSqlHelpers.csproj 14 | 15 | - name: Run tests 16 | run: dotnet test src/MsSqlHelpers.Tests/MsSqlHelpers.Tests.csproj 17 | 18 | - name: Publish to NuGet 19 | uses: brandedoutcast/publish-nuget@v2 20 | with: 21 | PROJECT_FILE_PATH: src/MsSqlHelpers/MsSqlHelpers.csproj 22 | NUGET_KEY: ${{secrets.NUGET_TOKEN}} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 alecgn 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MsSqlHelpers 2 | [![Build and tests status (mssql-helpers)](https://github.com/alecgn/mssql-helpers/workflows/build-and-test/badge.svg)](#) 3 | [![Nuget version (mssql-helpers)](https://img.shields.io/nuget/v/MsSqlHelpers)](https://nuget.org/packages/MsSqlHelpers) 4 | [![Nuget downloads (MsSqlHelpers)](https://img.shields.io/nuget/dt/MsSqlHelpers)](https://nuget.org/packages/MsSqlHelpers) 5 | 6 | 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). 7 | To allow IDENTITY INSERT ON, there's an optional parameter in method call (default mode OFF). 8 | 9 | **ADO.NET usage:** 10 | 11 | ```csharp 12 | using MsSqlHelpers; 13 | 14 | ... 15 | 16 | var mapper = new MapperBuilder() 17 | .SetTableName("People") // could be ommited if your table's name is the same as you entity's class name 18 | .AddMapping(person => person.FirstName, columnName: "Name") 19 | .AddMapping(person => person.LastName, columnName: "Surename") 20 | .AddMapping(person => person.DateOfBirth) // in this case property's name is the same as table column's name 21 | .Build(); 22 | var people = new List() 23 | { 24 | new Person() { FirstName = "John", LastName = "Lennon", DateOfBirth = new DateTime(1940, 10, 9) }, 25 | new Person() { FirstName = "Paul", LastName = "McCartney", DateOfBirth = new DateTime(1942, 6, 18) }, 26 | }; 27 | var connectionString = "Server=SERVER_ADDRESS;Database=DATABASE_NAME;User Id=USERNAME;Password=PASSWORD;"; 28 | var sqlQueriesAndParameters = new MsSqlQueryGenerator().GenerateParametrizedBulkInserts(mapper, people); 29 | 30 | using (var sqlConnection = new SqlConnection(connectionString)) 31 | { 32 | sqlConnection.Open(); 33 | 34 | // Default batch size: 1000 rows or (2100-1) parameters per insert. 35 | foreach (var (SqlQuery, SqlParameters) in sqlQueriesAndParameters) 36 | { 37 | using (SqlCommand sqlCommand = new SqlCommand(SqlQuery, sqlConnection)) 38 | { 39 | sqlCommand.Parameters.AddRange(SqlParameters.ToArray()); 40 | sqlCommand.ExecuteNonQuery(); 41 | } 42 | } 43 | } 44 | ``` 45 | 46 | **Entity Framework usage:** 47 | 48 | ```csharp 49 | using MsSqlHelpers; 50 | 51 | ... 52 | 53 | var mapper = new MapperBuilder() 54 | .SetTableName("People") // could be ommited if your table's name is the same as you entity's class name 55 | .AddMapping(person => person.FirstName, columnName: "Name") 56 | .AddMapping(person => person.LastName, columnName: "Surename") 57 | .AddMapping(person => person.DateOfBirth) // in this case property's name is the same as table column's name 58 | .Build(); 59 | var people = new List() 60 | { 61 | new Person() { FirstName = "John", LastName = "Lennon", DateOfBirth = new DateTime(1940, 10, 9) }, 62 | new Person() { FirstName = "Paul", LastName = "McCartney", DateOfBirth = new DateTime(1942, 6, 18) }, 63 | }; 64 | var sqlQueriesAndParameters = new MsSqlQueryGenerator().GenerateParametrizedBulkInserts(mapper, people); 65 | 66 | // Default batch size: 1000 rows or (2100-1) parameters per insert. 67 | foreach (var (SqlQuery, SqlParameters) in sqlQueriesAndParameters) 68 | { 69 | _context.Database.ExecuteSqlRaw(SqlQuery, SqlParameters); 70 | // Depracated but still works: _context.Database.ExecuteSqlCommand(SqlQuery, SqlParameters); 71 | } 72 | ``` 73 | 74 | **Dapper usage:** 75 | 76 | ```csharp 77 | using MsSqlHelpers; 78 | 79 | ... 80 | 81 | var mapper = new MapperBuilder() 82 | .SetTableName("People") // could be ommited if your table's name is the same as you entity's class name 83 | .AddMapping(person => person.FirstName, columnName: "Name") 84 | .AddMapping(person => person.LastName, columnName: "Surename") 85 | .AddMapping(person => person.DateOfBirth) // in this case property's name is the same as table column's name 86 | .Build(); 87 | var people = new List() 88 | { 89 | new Person() { FirstName = "John", LastName = "Lennon", DateOfBirth = new DateTime(1940, 10, 9) }, 90 | new Person() { FirstName = "Paul", LastName = "McCartney", DateOfBirth = new DateTime(1942, 6, 18) }, 91 | }; 92 | var connectionString = "Server=SERVER_ADDRESS;Database=DATABASE_NAME;User Id=USERNAME;Password=PASSWORD;"; 93 | var sqlQueriesAndDapperParameters = new MsSqlQueryGenerator().GenerateDapperParametrizedBulkInserts(mapper, people); 94 | 95 | using (var sqlConnection = new SqlConnection(connectionString)) 96 | { 97 | // Default batch size: 1000 rows or (2100-1) parameters per insert. 98 | foreach (var (SqlQuery, DapperDynamicParameters) in sqlQueriesAndDapperParameters) 99 | { 100 | sqlConnection.Execute(SqlQuery, DapperDynamicParameters); 101 | } 102 | } 103 | ``` 104 | -------------------------------------------------------------------------------- /src/MsSqlHelpers.Tests/MsSqlHelpers.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | false 7 | 8 | 1.4.0 9 | 10 | 1.4.0 11 | 12 | 1.4.0 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/MsSqlHelpers.Tests/MsSqlQueryGeneratorTests.cs: -------------------------------------------------------------------------------- 1 | using Bogus; 2 | using FluentAssertions; 3 | using Microsoft.Data.SqlClient; 4 | using NUnit.Framework; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Data; 8 | using System.Linq; 9 | 10 | namespace MsSqlHelpers.Tests 11 | { 12 | public class MsSqlQueryGeneratorTests 13 | { 14 | private MsSqlQueryGenerator _msSqlQueryGenerator; 15 | 16 | [OneTimeSetUp] 17 | public void Setup() 18 | { 19 | _msSqlQueryGenerator = new MsSqlQueryGenerator(); 20 | } 21 | 22 | [TestCase(null)] 23 | [TestCase("")] 24 | [TestCase(" ")] 25 | [Test] 26 | public void ShouldThrowArgumentException_WhenMapperTableName_IsNullEmptyOrWhiteSpace(string tableName) 27 | { 28 | var mapper = new MapperBuilder() 29 | .SetTableName(tableName) 30 | .AddMapping(person => person.FirstName) 31 | .AddMapping(person => person.LastName) 32 | .AddMapping(person => person.DateOfBirth, columnName: "Birthday") 33 | .Build(); 34 | var people = new Faker() 35 | .RuleFor(person => person.FirstName, fakePerson => fakePerson.Person.FirstName) 36 | .RuleFor(person => person.LastName, fakePerson => fakePerson.Person.LastName) 37 | .RuleFor(person => person.DateOfBirth, fakePerson => fakePerson.Person.DateOfBirth) 38 | .GenerateLazy(2); 39 | 40 | Action act = () => _msSqlQueryGenerator.GenerateParametrizedBulkInserts(mapper, people); 41 | 42 | act.Should().ThrowExactly(); 43 | } 44 | 45 | [TestCase(null)] 46 | [TestCaseSource(nameof(GetEmptyMapping))] 47 | [Test] 48 | public void ShouldThrowArgumentException_WhenMapperMappings_AreNullOrEmpty(Dictionary mappings) 49 | { 50 | var tableName = Guid.NewGuid().ToString(); 51 | var mapper = new MapperBuilder() 52 | .SetTableName(tableName) 53 | .SetMappings(mappings) 54 | .Build(); 55 | var people = new Faker() 56 | .RuleFor(person => person.FirstName, fakePerson => fakePerson.Person.FirstName) 57 | .RuleFor(person => person.LastName, fakePerson => fakePerson.Person.LastName) 58 | .RuleFor(person => person.DateOfBirth, fakePerson => fakePerson.Person.DateOfBirth) 59 | .GenerateLazy(2); 60 | 61 | Action act = () => _msSqlQueryGenerator.GenerateParametrizedBulkInserts(mapper, people); 62 | 63 | act.Should().ThrowExactly(); 64 | } 65 | 66 | [Test] 67 | public void ShouldThrowArgumentException_WhenMapperMappings_HaveInvalidPropertyNames() 68 | { 69 | var tableName = Guid.NewGuid().ToString(); 70 | var mappings = new Dictionary() 71 | { 72 | { $"{nameof(Person.FirstName)}_Invalid", nameof(Person.FirstName) }, 73 | { nameof(Person.LastName), nameof(Person.LastName) }, 74 | { nameof(Person.DateOfBirth), "Birthday" }, 75 | }; 76 | var mapper = new MapperBuilder() 77 | .SetTableName(tableName) 78 | .SetMappings(mappings) 79 | .Build(); 80 | var people = new Faker() 81 | .RuleFor(person => person.FirstName, fakePerson => fakePerson.Person.FirstName) 82 | .RuleFor(person => person.LastName, fakePerson => fakePerson.Person.LastName) 83 | .RuleFor(person => person.DateOfBirth, fakePerson => fakePerson.Person.DateOfBirth) 84 | .GenerateLazy(2); 85 | 86 | Action act = () => _msSqlQueryGenerator.GenerateParametrizedBulkInserts(mapper, people); 87 | 88 | act.Should().ThrowExactly(); 89 | } 90 | 91 | [TestCase(null)] 92 | [TestCaseSource(nameof(GetEmptyCollectionOfPerson))] 93 | [Test] 94 | public void ShouldThrowArgumentException_WhenParameterCollectionOfObjects_IsNullOrEmpty(IEnumerable people) 95 | { 96 | var tableName = Guid.NewGuid().ToString(); 97 | var mapper = new MapperBuilder() 98 | .SetTableName(tableName) 99 | .AddMapping(person => person.FirstName) 100 | .AddMapping(person => person.LastName) 101 | .AddMapping(person => person.DateOfBirth, columnName: "Birthday") 102 | .Build(); 103 | 104 | Action act = () => _msSqlQueryGenerator.GenerateParametrizedBulkInserts(mapper, people); 105 | 106 | act.Should().ThrowExactly(); 107 | } 108 | 109 | [Test] 110 | public void ShouldValidateIfGeneratedSqlAndParameters_AreEquals_ExpectedSqlAndParameters() 111 | { 112 | var tableName = Guid.NewGuid().ToString(); 113 | var mapper = new MapperBuilder() 114 | .SetTableName(tableName) 115 | .AddMapping(person => person.FirstName) 116 | .AddMapping(person => person.LastName) 117 | .AddMapping(person => person.DateOfBirth, columnName: "Birthday") 118 | .Build(); 119 | var people = new Faker() 120 | .RuleFor(person => person.FirstName, fakePerson => fakePerson.Person.FirstName) 121 | .RuleFor(person => person.LastName, fakePerson => fakePerson.Person.LastName) 122 | .RuleFor(person => person.DateOfBirth, fakePerson => fakePerson.Person.DateOfBirth) 123 | .Generate(2); 124 | var sqlParameters = CreateSqlParameters(mapper, people); 125 | var expectedResult = new List<(string SqlQuery, IEnumerable SqlParameters)>() 126 | { 127 | (CreateSqlInsert(mapper, sqlParameters), sqlParameters) 128 | }; 129 | var result = _msSqlQueryGenerator.GenerateParametrizedBulkInserts(mapper, people); 130 | 131 | result.Should().BeEquivalentTo(expectedResult.AsEnumerable()); 132 | } 133 | 134 | [Test] 135 | public void ShouldValidateIfGeneratedSqlAndParameters_AreEquals_ExpectedSqlAndParameters_WhenAllowIdentityInsertIsSetToTrue() 136 | { 137 | var tableName = Guid.NewGuid().ToString(); 138 | var mapper = new MapperBuilder() 139 | .SetTableName(tableName) 140 | .AddMapping(person => person.FirstName) 141 | .AddMapping(person => person.LastName) 142 | .AddMapping(person => person.DateOfBirth, columnName: "Birthday") 143 | .Build(); 144 | var people = new Faker() 145 | .RuleFor(person => person.FirstName, fakePerson => fakePerson.Person.FirstName) 146 | .RuleFor(person => person.LastName, fakePerson => fakePerson.Person.LastName) 147 | .RuleFor(person => person.DateOfBirth, fakePerson => fakePerson.Person.DateOfBirth) 148 | .Generate(2); 149 | var sqlParameters = CreateSqlParameters(mapper, people); 150 | var expectedResult = new List<(string SqlQuery, IEnumerable SqlParameters)>() 151 | { 152 | (CreateSqlInsert(mapper, sqlParameters, allowIdentityInsert: true), sqlParameters) 153 | }; 154 | var result = _msSqlQueryGenerator.GenerateParametrizedBulkInserts(mapper, people, allowIdentityInsert: true); 155 | 156 | result.Should().BeEquivalentTo(expectedResult.AsEnumerable()); 157 | } 158 | 159 | [Test] 160 | public void ShouldSplitGeneratedSqlAndParameters_WhenCollectionOfObjects_IsMoreThanMaxAllowedBatchSize() 161 | { 162 | var tableName = Guid.NewGuid().ToString(); 163 | var mapper = new MapperBuilder() 164 | .SetTableName(tableName) 165 | .AddMapping(person => person.FirstName) 166 | .Build(); 167 | var people = new Faker() 168 | .RuleFor(person => person.FirstName, fakePerson => fakePerson.Person.FirstName) 169 | .GenerateLazy(MsSqlQueryGenerator.MaxAllowedBatchSize + 1); 170 | 171 | var result = _msSqlQueryGenerator.GenerateParametrizedBulkInserts(mapper, people); 172 | 173 | result.Count().Should().Be(2); 174 | } 175 | 176 | [Test] 177 | public void ShouldSplitGeneratedSqlAndParameters_WhenParametersCount_IsMoreThanMaxAllowedSqlParametersCount() 178 | { 179 | var tableName = Guid.NewGuid().ToString(); 180 | var mapper = new MapperBuilder() 181 | .SetTableName(tableName) 182 | .AddMapping(person => person.FirstName) 183 | .AddMapping(person => person.LastName) 184 | .AddMapping(person => person.DateOfBirth, columnName: "Birthday") 185 | .Build(); 186 | // 3 properties/parameters * 700 entities = 2,100 properties/parameters, wich is greater than MaxAllowedSqlParametersCount (2100-1) 187 | var people = new Faker() 188 | .RuleFor(person => person.FirstName, fakePerson => fakePerson.Person.FirstName) 189 | .RuleFor(person => person.LastName, fakePerson => fakePerson.Person.LastName) 190 | .RuleFor(person => person.DateOfBirth, fakePerson => fakePerson.Person.DateOfBirth) 191 | .GenerateLazy(700); 192 | 193 | var result = _msSqlQueryGenerator.GenerateParametrizedBulkInserts(mapper, people); 194 | 195 | result.Count().Should().Be(2); 196 | } 197 | 198 | [Test] 199 | public void ShouldFillAutomaticallyMapperTableNameWithEntityClassName_WhenTableName_IsNotProvided() 200 | { 201 | var mapper = new MapperBuilder() // -> TableName not set by constructor 202 | //.SetTableName(tableName) -> TableName not set by method 203 | .AddMapping(person => person.FirstName) 204 | .AddMapping(person => person.LastName) 205 | .AddMapping(person => person.DateOfBirth, columnName: "Birthday") 206 | .Build(); 207 | var people = new Faker() 208 | .RuleFor(person => person.FirstName, fakePerson => fakePerson.Person.FirstName) 209 | .RuleFor(person => person.LastName, fakePerson => fakePerson.Person.LastName) 210 | .RuleFor(person => person.DateOfBirth, fakePerson => fakePerson.Person.DateOfBirth) 211 | .Generate(2); 212 | var sqlParameters = CreateSqlParameters(mapper, people); 213 | var expectedResult = new List<(string SqlQuery, IEnumerable SqlParameters)>() 214 | { 215 | (CreateSqlInsert(mapper, sqlParameters, allowIdentityInsert: true), sqlParameters) 216 | }; 217 | var result = _msSqlQueryGenerator.GenerateParametrizedBulkInserts(mapper, people, allowIdentityInsert: true); 218 | 219 | result.Should().BeEquivalentTo(expectedResult.AsEnumerable()); 220 | } 221 | 222 | private static Dictionary GetEmptyMapping() => new Dictionary(); 223 | 224 | private static IEnumerable GetEmptyCollectionOfPerson() => new Person[] { }; 225 | 226 | private static List CreateSqlParameters(Mapper mapper, IEnumerable collectionOfObjects) 227 | where T : class 228 | { 229 | var sqlParameters = new List(); 230 | var parameterIndex = 0; 231 | 232 | foreach (var entry in collectionOfObjects) 233 | { 234 | foreach (var mapping in mapper.Mappings) 235 | { 236 | sqlParameters.Add(new SqlParameter($"@p{parameterIndex}", GetPropertyValue(entry, mapping.Key))); 237 | parameterIndex++; 238 | } 239 | } 240 | 241 | return sqlParameters; 242 | } 243 | 244 | private static object GetPropertyValue(object @object, string propertyName) => 245 | @object.GetType().GetProperty(propertyName).GetValue(@object, null); 246 | 247 | private string CreateSqlInsert(Mapper mapper, List sqlParameters, bool allowIdentityInsert = false) where T : class => 248 | "SET NOCOUNT ON; " + 249 | (allowIdentityInsert ? $"SET IDENTITY_INSERT [{mapper.TableName}] ON; " : "") + 250 | $"INSERT INTO [{mapper.TableName}] ([{mapper.Mappings[nameof(Person.FirstName)]}], [{mapper.Mappings[nameof(Person.LastName)]}], [{mapper.Mappings[nameof(Person.DateOfBirth)]}]) " + 251 | $"VALUES ({sqlParameters[0].ParameterName}, {sqlParameters[1].ParameterName}, {sqlParameters[2].ParameterName}), " + 252 | $"({sqlParameters[3].ParameterName}, {sqlParameters[4].ParameterName}, {sqlParameters[5].ParameterName});"; 253 | } 254 | } -------------------------------------------------------------------------------- /src/MsSqlHelpers.Tests/Person.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace MsSqlHelpers.Tests 4 | { 5 | public class Person 6 | { 7 | public int Id { get; set; } 8 | public string FirstName { get; set; } 9 | public string LastName { get; set; } 10 | public DateTime DateOfBirth { get; set; } 11 | public float Height { get; set; } 12 | public float Weight { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/MsSqlHelpers.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31005.135 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsSqlHelpers", "MsSqlHelpers\MsSqlHelpers.csproj", "{73485DA9-1C01-4439-BB56-86143CC2F83E}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MsSqlHelpers.Tests", "MsSqlHelpers.Tests\MsSqlHelpers.Tests.csproj", "{4DC2EB36-9F39-4953-88E4-63338BCAFADF}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {73485DA9-1C01-4439-BB56-86143CC2F83E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {73485DA9-1C01-4439-BB56-86143CC2F83E}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {73485DA9-1C01-4439-BB56-86143CC2F83E}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {73485DA9-1C01-4439-BB56-86143CC2F83E}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {4DC2EB36-9F39-4953-88E4-63338BCAFADF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {4DC2EB36-9F39-4953-88E4-63338BCAFADF}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {4DC2EB36-9F39-4953-88E4-63338BCAFADF}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {4DC2EB36-9F39-4953-88E4-63338BCAFADF}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {FE880F4A-B369-48CD-BDD0-0B07AC3E5067} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /src/MsSqlHelpers/Enums/MsSqlUserLanguage.cs: -------------------------------------------------------------------------------- 1 | namespace MsSqlHelpers.Enums 2 | { 3 | public enum MsSqlUserLanguage 4 | { 5 | EnglishUnitedStates, 6 | PortugueseBrazilian 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/MsSqlHelpers/Extensions/Extensions.cs: -------------------------------------------------------------------------------- 1 | using MsSqlHelpers.Enums; 2 | using System; 3 | using System.Globalization; 4 | 5 | namespace MsSqlHelpers.Extensions 6 | { 7 | public static class MsSqlExtensions 8 | { 9 | private const string SqlNull = "null"; 10 | 11 | public static string ToSqlValue(this object @object, MsSqlUserLanguage msSqlUserLanguage = MsSqlUserLanguage.EnglishUnitedStates) => 12 | HandleSqlObject(@object, msSqlUserLanguage); 13 | 14 | private static string HandleSqlObject(object @object, MsSqlUserLanguage msSqlUserLanguage) 15 | { 16 | if (@object is null) 17 | { 18 | return SqlNull; 19 | } 20 | 21 | if (@object is string) 22 | { 23 | return HandleSqlString((string)@object); 24 | } 25 | 26 | if (@object is decimal) 27 | { 28 | return HandleSqlDecimal((decimal)@object, msSqlUserLanguage); 29 | } 30 | 31 | if (@object is decimal?) 32 | { 33 | return HandleSqlNullableDecimal((decimal?)@object, msSqlUserLanguage); 34 | } 35 | 36 | if (@object is DateTime) 37 | { 38 | return HandleSqlDateTime((DateTime)@object, msSqlUserLanguage); 39 | } 40 | 41 | if (@object is DateTime?) 42 | { 43 | return HandleSqlNullableDateTime((DateTime?)@object, msSqlUserLanguage); 44 | } 45 | 46 | return @object.ToString(); 47 | } 48 | 49 | private static string HandleSqlString(string @string) => $"'{@string}'"; 50 | 51 | private static string HandleSqlDecimal(decimal @decimal, MsSqlUserLanguage msSqlUserLanguage) => 52 | @decimal.ToString(msSqlUserLanguage.GetCultureInfo()); 53 | 54 | private static CultureInfo GetCultureInfo(this MsSqlUserLanguage msSqlUserLanguage) 55 | { 56 | switch (msSqlUserLanguage) 57 | { 58 | case MsSqlUserLanguage.PortugueseBrazilian: 59 | return new CultureInfo("pt-BR"); 60 | case MsSqlUserLanguage.EnglishUnitedStates: 61 | default: 62 | return new CultureInfo("en-US"); 63 | } 64 | } 65 | 66 | private static string HandleSqlNullableDecimal(decimal? @nullableDecimal, MsSqlUserLanguage msSqlUserLanguage) => 67 | @nullableDecimal?.ToString(msSqlUserLanguage.GetCultureInfo()); 68 | 69 | private static string HandleSqlDateTime(DateTime dateTime, MsSqlUserLanguage msSqlUserLanguage) => 70 | dateTime.ToString(msSqlUserLanguage.GetDateTimeFormat()); 71 | 72 | private static string GetDateTimeFormat(this MsSqlUserLanguage msSqlUserLanguage) 73 | { 74 | switch (msSqlUserLanguage) 75 | { 76 | case MsSqlUserLanguage.PortugueseBrazilian: 77 | return "dd-MM-yyyy HH:mm:ss.fff"; 78 | case MsSqlUserLanguage.EnglishUnitedStates: 79 | default: 80 | return "yyyy-MM-dd HH:mm:ss.fff"; 81 | } 82 | } 83 | 84 | private static string HandleSqlNullableDateTime(DateTime? nullableDateTime, MsSqlUserLanguage msSqlUserLanguage) => 85 | nullableDateTime?.ToString(msSqlUserLanguage.GetDateTimeFormat()); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/MsSqlHelpers/Icon/mssql-helpers-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alecgn/mssql-helpers/a09b3928b544d69a34337a7a636a09aea2edf0bf/src/MsSqlHelpers/Icon/mssql-helpers-icon.png -------------------------------------------------------------------------------- /src/MsSqlHelpers/Interfaces/IMsSqlQueryGenerator.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | #if NETFRAMEWORK 3 | using System.Data.SqlClient; 4 | #else 5 | using Microsoft.Data.SqlClient; 6 | #endif 7 | using System.Collections.Generic; 8 | 9 | namespace MsSqlHelpers.Interfaces 10 | { 11 | public interface IMsSqlQueryGenerator 12 | { 13 | IEnumerable<(string SqlQuery, IEnumerable SqlParameters)> GenerateParametrizedBulkInserts( 14 | Mapper mapper, 15 | IEnumerable collectionOfObjects, 16 | bool allowIdentityInsert = false) 17 | where T : class; 18 | 19 | IEnumerable<(string SqlQuery, DynamicParameters DapperDynamicParameters)> GenerateDapperParametrizedBulkInserts( 20 | Mapper mapper, 21 | IEnumerable collectionOfObjects, 22 | bool allowIdentityInsert = false) 23 | where T : class; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/MsSqlHelpers/Mapper.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace MsSqlHelpers 5 | { 6 | public class Mapper 7 | where T : class 8 | { 9 | public string TableName { get; set; } 10 | public Dictionary Mappings { get; set; } 11 | 12 | public Mapper() 13 | { 14 | Mappings = new Dictionary(); 15 | } 16 | 17 | public Mapper(string tableName) 18 | { 19 | TableName = tableName; 20 | Mappings = new Dictionary(); 21 | } 22 | 23 | public (bool IsValid, List ValidationErrors) Validate() 24 | { 25 | var isValid = true; 26 | var validationErrors = new List(); 27 | 28 | if (string.IsNullOrWhiteSpace(TableName)) 29 | { 30 | isValid = false; 31 | validationErrors.Add($"[{nameof(Mapper)}.{nameof(TableName)}] can not be null, empty or white-space."); 32 | } 33 | 34 | if (Mappings is null || Mappings.Count == 0) 35 | { 36 | isValid = false; 37 | validationErrors.Add($"[{nameof(Mapper)}.{nameof(Mappings)}] can not be null or empty."); 38 | } 39 | 40 | var propertyNamesNotFound = Mappings? 41 | .Select(mapping => mapping.Key) 42 | .Except(typeof(T).GetProperties() 43 | .Select(propertyInfo => propertyInfo.Name)); 44 | 45 | if (!(propertyNamesNotFound is null) && propertyNamesNotFound.Any()) 46 | { 47 | isValid = false; 48 | validationErrors.Add($"Properties [{string.Join(", ", propertyNamesNotFound)}] in [{nameof(Mapper)}.{nameof(Mappings)}] not found in the source object [{typeof(T)}]."); 49 | } 50 | 51 | return (IsValid: isValid, ValidationErrors: validationErrors); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/MsSqlHelpers/MapperBuilder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq.Expressions; 4 | using System.Reflection; 5 | 6 | namespace MsSqlHelpers 7 | { 8 | public class MapperBuilder where T : class 9 | { 10 | private readonly Mapper _mapper; 11 | 12 | public MapperBuilder() 13 | { 14 | _mapper = new Mapper(); 15 | _mapper.TableName = nameof(T); 16 | } 17 | 18 | public MapperBuilder(string tableName) 19 | { 20 | _mapper = new Mapper(tableName); 21 | } 22 | 23 | public MapperBuilder SetTableName(string tableName) 24 | { 25 | _mapper.TableName = tableName; 26 | 27 | return this; 28 | } 29 | 30 | /// 31 | /// Use this method overload if your table column's name is different from your property's name 32 | /// 33 | /// 34 | /// 35 | /// 36 | public MapperBuilder AddMapping(string propertyName, string columnName) 37 | { 38 | _mapper.Mappings.Add(propertyName, columnName); 39 | 40 | return this; 41 | } 42 | 43 | /// 44 | /// Use this method overload if your table column's name is the same as your property's name 45 | /// 46 | /// 47 | /// 48 | public MapperBuilder AddMapping(string propertyColumnName) 49 | { 50 | _mapper.Mappings.Add(propertyColumnName, propertyColumnName); 51 | 52 | return this; 53 | } 54 | 55 | /// 56 | /// Use this method overload if your table column's name is different from your property's name 57 | /// 58 | /// 59 | /// 60 | /// 61 | /// 62 | public MapperBuilder AddMapping( 63 | Expression> propertyLambda, string columnName) 64 | { 65 | var memberExpression = propertyLambda.Body as MemberExpression ?? 66 | throw new ArgumentException($"{nameof(propertyLambda)}.Body must be a MemberExpression.", nameof(propertyLambda)); 67 | var propertyInfo = memberExpression.Member as PropertyInfo ?? 68 | throw new ArgumentException($"{nameof(memberExpression)}.Member must be a PropertyInfo.", nameof(propertyLambda)); 69 | _mapper.Mappings.Add(propertyInfo.Name, columnName); 70 | 71 | return this; 72 | } 73 | 74 | /// 75 | /// Use this method overload if your table column's name is the same as your property's name 76 | /// 77 | /// 78 | /// 79 | /// 80 | public MapperBuilder AddMapping( 81 | Expression> propertyLambda) 82 | { 83 | var memberExpression = propertyLambda.Body as MemberExpression ?? 84 | throw new ArgumentException($"{nameof(propertyLambda)}.Body must be a MemberExpression.", nameof(propertyLambda)); 85 | var propertyInfo = memberExpression.Member as PropertyInfo ?? 86 | throw new ArgumentException($"{nameof(memberExpression)}.Member must be a PropertyInfo.", nameof(propertyLambda)); 87 | _mapper.Mappings.Add(propertyInfo.Name, propertyInfo.Name); 88 | 89 | return this; 90 | } 91 | 92 | public MapperBuilder SetMappings(Dictionary mappings) 93 | { 94 | _mapper.Mappings = mappings; 95 | 96 | return this; 97 | } 98 | 99 | public Mapper Build() => _mapper; 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/MsSqlHelpers/MsSqlHelpers.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0 5 | true 6 | 1.4.0 7 | Alessandro Cagliostro Goncalves Neves 8 | Alessandro Cagliostro Goncalves Neves 9 | 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). 10 | MIT 11 | https://github.com/alecgn/mssql-helpers 12 | https://github.com/alecgn/mssql-helpers 13 | 1.4.0 14 | 1.4.0 15 | - Added methods to insert only a single entity class. 16 | Alessandro Cagliostro Goncalves Neves, 2021 17 | mssql-helpers-icon.png 18 | ms sql server database dapper entity framework ado bulk insert net c# c-sharp 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | True 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /src/MsSqlHelpers/MsSqlQueryGenerator.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using MsSqlHelpers.Interfaces; 3 | #if NETFRAMEWORK 4 | using System.Data.SqlClient; 5 | #else 6 | using Microsoft.Data.SqlClient; 7 | #endif 8 | using System; 9 | using System.Collections.Generic; 10 | using System.Linq; 11 | using System.Reflection; 12 | using System.Text; 13 | 14 | namespace MsSqlHelpers 15 | { 16 | public class MsSqlQueryGenerator : IMsSqlQueryGenerator 17 | { 18 | public const int MaxAllowedBatchSize = 1000; 19 | public const int MaxAllowedSqlParametersCount = (2100 - 1); 20 | 21 | public (string SqlQuery, IEnumerable SqlParameters) GenerateParametrizedBulkInsert( 22 | Mapper mapper, 23 | T @entityObject, 24 | bool allowIdentityInsert = false) 25 | where T : class => 26 | GenerateParametrizedBulkInserts(mapper, new T[] { @entityObject }, allowIdentityInsert).FirstOrDefault(); 27 | 28 | public IEnumerable<(string SqlQuery, IEnumerable SqlParameters)> GenerateParametrizedBulkInserts( 29 | Mapper mapper, 30 | IEnumerable collectionOfObjects, 31 | bool allowIdentityInsert = false) 32 | where T : class 33 | { 34 | ValidateParameters(mapper, collectionOfObjects); 35 | 36 | return GenerateSqlQueriesAndParameters(mapper, collectionOfObjects, allowIdentityInsert); 37 | } 38 | 39 | public (string SqlQuery, DynamicParameters DapperDynamicParameters) GenerateDapperParametrizedBulkInsert( 40 | Mapper mapper, 41 | T @entityObject, 42 | bool allowIdentityInsert = false) 43 | where T : class => 44 | GenerateDapperParametrizedBulkInserts(mapper, new T[] { @entityObject }, allowIdentityInsert).FirstOrDefault(); 45 | 46 | public IEnumerable<(string SqlQuery, DynamicParameters DapperDynamicParameters)> GenerateDapperParametrizedBulkInserts( 47 | Mapper mapper, 48 | IEnumerable collectionOfObjects, 49 | bool allowIdentityInsert = false) 50 | where T : class 51 | { 52 | ValidateParameters(mapper, collectionOfObjects); 53 | 54 | return GenerateSqlQueriesAndDapperDynamicParameters(mapper, collectionOfObjects, allowIdentityInsert); 55 | } 56 | 57 | private static void ValidateParameters(Mapper mapper, IEnumerable collectionOfObjects) 58 | where T : class 59 | { 60 | var mapperValidationResult = mapper.Validate(); 61 | 62 | if (!mapperValidationResult.IsValid) 63 | { 64 | throw new ArgumentException(string.Join(Environment.NewLine, mapperValidationResult.ValidationErrors)); 65 | } 66 | 67 | if (collectionOfObjects is null || !collectionOfObjects.Any()) 68 | { 69 | throw new ArgumentException($@"Parameter ""{nameof(collectionOfObjects)}"" can not be null or empty.", nameof(collectionOfObjects)); 70 | } 71 | } 72 | 73 | private IEnumerable<(string SqlQuery, IEnumerable SqlParameters)> GenerateSqlQueriesAndParameters( 74 | Mapper mapper, 75 | IEnumerable collectionOfObjects, 76 | bool allowIdentityInsert = false) 77 | where T : class 78 | { 79 | var numberOfObjectsPerInsert = ((int)Math.Floor((double)MaxAllowedSqlParametersCount / mapper.Mappings.Count)); 80 | numberOfObjectsPerInsert = Math.Min(numberOfObjectsPerInsert, MaxAllowedBatchSize); 81 | var numberOfBatches = (int)Math.Ceiling((double)collectionOfObjects.Count() / numberOfObjectsPerInsert); 82 | 83 | for (int batchNumber = 1; batchNumber <= numberOfBatches; batchNumber++) 84 | { 85 | var collectionOfObjectsToInsert = collectionOfObjects.Skip((batchNumber - 1) * numberOfObjectsPerInsert).Take(numberOfObjectsPerInsert); 86 | var columnsDefinition = GenerateColumnsDefinitionSql(mapper); 87 | var values = GenerateValuesSql(collectionOfObjectsToInsert, mapper); 88 | var sqlQuery = new StringBuilder() 89 | .Append("SET NOCOUNT ON; ") 90 | .Append(allowIdentityInsert ? $"SET IDENTITY_INSERT [{mapper.TableName}] ON; " : "") 91 | .Append($"INSERT INTO [{mapper.TableName}] ") 92 | .Append(columnsDefinition) 93 | .Append(" VALUES ") 94 | .Append(values); 95 | 96 | yield return (SqlQuery: sqlQuery.ToString(), SqlParameters: GenerateSqlParameters(collectionOfObjectsToInsert, mapper)); 97 | } 98 | } 99 | 100 | private IEnumerable<(string SqlQuery, DynamicParameters DapperDynamicParameters)> GenerateSqlQueriesAndDapperDynamicParameters( 101 | Mapper mapper, 102 | IEnumerable collectionOfObjects, 103 | bool allowIdentityInsert = false) 104 | where T : class 105 | { 106 | var numberOfObjectsPerInsert = ((int)Math.Floor((double)MaxAllowedSqlParametersCount / mapper.Mappings.Count)); 107 | numberOfObjectsPerInsert = Math.Min(numberOfObjectsPerInsert, MaxAllowedBatchSize); 108 | var numberOfBatches = (int)Math.Ceiling((double)collectionOfObjects.Count() / numberOfObjectsPerInsert); 109 | 110 | for (int batchNumber = 1; batchNumber <= numberOfBatches; batchNumber++) 111 | { 112 | var collectionOfObjectsToInsert = collectionOfObjects.Skip((batchNumber - 1) * numberOfObjectsPerInsert).Take(numberOfObjectsPerInsert); 113 | var columnsDefinition = GenerateColumnsDefinitionSql(mapper); 114 | var values = GenerateValuesSql(collectionOfObjectsToInsert, mapper); 115 | var sqlQuery = new StringBuilder() 116 | .Append("SET NOCOUNT ON; ") 117 | .Append(allowIdentityInsert ? $"SET IDENTITY_INSERT [{mapper.TableName}] ON; " : "") 118 | .Append($"INSERT INTO [{mapper.TableName}] ") 119 | .Append(columnsDefinition) 120 | .Append(" VALUES ") 121 | .Append(values); 122 | 123 | yield return (SqlQuery: sqlQuery.ToString(), DapperDynamicParameters: GenerateDapperDynamicParameters(collectionOfObjectsToInsert, mapper)); 124 | } 125 | } 126 | 127 | private StringBuilder GenerateColumnsDefinitionSql(Mapper mapper) where T : class => new StringBuilder() 128 | .Append('(') 129 | .Append(string.Join(", ", mapper.Mappings.Select(mapping => $"[{mapping.Value}]"))) 130 | .Append(')'); 131 | 132 | private StringBuilder GenerateValuesSql(IEnumerable collectionOfObjects, Mapper mapper) 133 | where T : class 134 | { 135 | var valuesSql = new StringBuilder(); 136 | var objectsProcessed = 0; 137 | var offset = 0; 138 | var collectionOfObjectsCount = collectionOfObjects.Count(); 139 | 140 | foreach (var @object in collectionOfObjects) 141 | { 142 | var objectPropertiesInfo = @object.GetType().GetProperties(); 143 | var filteredObjectPropertiesInfo = objectPropertiesInfo.Where(pi => mapper.Mappings.Keys.Contains(pi.Name)); 144 | var propertyValues = GetPropertyValues(filteredObjectPropertiesInfo, @object); 145 | valuesSql 146 | .Append('(') 147 | .Append(string.Join(", ", Enumerable.Range(offset, propertyValues.Count).Select(parameterIndex => $"@p{parameterIndex}"))) 148 | .Append(')'); 149 | objectsProcessed++; 150 | offset += propertyValues.Count; 151 | valuesSql.Append(objectsProcessed < collectionOfObjectsCount ? ", " : ";"); 152 | } 153 | 154 | return valuesSql; 155 | } 156 | 157 | private List GetPropertyValues(IEnumerable propertiesInfo, object @object) 158 | { 159 | var propertyValues = new List(); 160 | 161 | foreach (var propertyInfo in propertiesInfo) 162 | { 163 | propertyValues.Add(GetPropertyValue(@object, propertyInfo.Name)); 164 | } 165 | 166 | return propertyValues; 167 | } 168 | 169 | private object GetPropertyValue(object @object, string propertyName) => 170 | @object.GetType().GetProperty(propertyName).GetValue(@object, null); 171 | 172 | private IEnumerable GenerateSqlParameters(IEnumerable collectionOfObjects, Mapper mapper) 173 | where T : class 174 | { 175 | var sqlParameters = new List(); 176 | var parameterIndex = 0; 177 | 178 | foreach (var @object in collectionOfObjects) 179 | { 180 | foreach (var mapping in mapper.Mappings) 181 | { 182 | sqlParameters.Add(new SqlParameter($"@p{parameterIndex}", GetPropertyValue(@object, mapping.Key) ?? DBNull.Value)); 183 | parameterIndex++; 184 | } 185 | } 186 | 187 | return sqlParameters; 188 | } 189 | 190 | private DynamicParameters GenerateDapperDynamicParameters(IEnumerable collectionOfObjects, Mapper mapper) 191 | where T : class 192 | { 193 | var dapperDynamicParameters = new DynamicParameters(); 194 | var parameterIndex = 0; 195 | 196 | foreach (var @object in collectionOfObjects) 197 | { 198 | foreach (var mapping in mapper.Mappings) 199 | { 200 | dapperDynamicParameters.Add($"@p{parameterIndex}", GetPropertyValue(@object, mapping.Key)); 201 | parameterIndex++; 202 | } 203 | } 204 | 205 | return dapperDynamicParameters; 206 | } 207 | } 208 | } 209 | --------------------------------------------------------------------------------