├── .gitignore ├── DapperASPNetCore ├── DapperASPNetCore.sln └── DapperASPNetCore │ ├── Context │ └── DapperContext.cs │ ├── Contracts │ └── ICompanyRepository.cs │ ├── Controllers │ └── CompaniesController.cs │ ├── DapperASPNetCore.csproj │ ├── Dto │ ├── CompanyForCreationDto.cs │ └── CompanyForUpdateDto.cs │ ├── Entities │ ├── Company.cs │ └── Employee.cs │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── Repository │ └── CompanyRepository.cs │ ├── Startup.cs │ ├── appsettings.Development.json │ └── appsettings.json ├── Initial Script with Data.sql ├── LICENSE └── README.md /.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 | -------------------------------------------------------------------------------- /DapperASPNetCore/DapperASPNetCore.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31205.134 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DapperASPNetCore", "DapperASPNetCore\DapperASPNetCore.csproj", "{0E176561-F079-442C-993F-CBC45085C83D}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {0E176561-F079-442C-993F-CBC45085C83D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {0E176561-F079-442C-993F-CBC45085C83D}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {0E176561-F079-442C-993F-CBC45085C83D}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {0E176561-F079-442C-993F-CBC45085C83D}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {BF654755-4097-494C-B2B7-A55BC5A832CC} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /DapperASPNetCore/DapperASPNetCore/Context/DapperContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Data.SqlClient; 2 | using Microsoft.Extensions.Configuration; 3 | using System.Data; 4 | 5 | namespace DapperASPNetCore.Context 6 | { 7 | public class DapperContext 8 | { 9 | private readonly IConfiguration _configuration; 10 | private readonly string _connectionString; 11 | 12 | public DapperContext(IConfiguration configuration) 13 | { 14 | _configuration = configuration; 15 | _connectionString = _configuration.GetConnectionString("SqlConnection"); 16 | } 17 | 18 | public IDbConnection CreateConnection() 19 | => new SqlConnection(_connectionString); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /DapperASPNetCore/DapperASPNetCore/Contracts/ICompanyRepository.cs: -------------------------------------------------------------------------------- 1 | using DapperASPNetCore.Dto; 2 | using DapperASPNetCore.Entities; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | namespace DapperASPNetCore.Contracts 9 | { 10 | public interface ICompanyRepository 11 | { 12 | public Task> GetCompanies(); 13 | public Task GetCompany(int id); 14 | public Task CreateCompany(CompanyForCreationDto company); 15 | public Task UpdateCompany(int id, CompanyForUpdateDto company); 16 | public Task DeleteCompany(int id); 17 | public Task GetCompanyByEmployeeId(int id); 18 | public Task GetCompanyEmployeesMultipleResults(int id); 19 | public Task> GetCompaniesEmployeesMultipleMapping(); 20 | public Task CreateMultipleCompanies(List companies); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /DapperASPNetCore/DapperASPNetCore/Controllers/CompaniesController.cs: -------------------------------------------------------------------------------- 1 | using DapperASPNetCore.Contracts; 2 | using DapperASPNetCore.Dto; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.AspNetCore.Mvc; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | 10 | namespace DapperASPNetCore.Controllers 11 | { 12 | [Route("api/companies")] 13 | [ApiController] 14 | public class CompaniesController : ControllerBase 15 | { 16 | private readonly ICompanyRepository _companyRepo; 17 | 18 | public CompaniesController(ICompanyRepository companyRepo) 19 | { 20 | _companyRepo = companyRepo; 21 | } 22 | 23 | [HttpGet] 24 | public async Task GetCompanies() 25 | { 26 | try 27 | { 28 | var companies = await _companyRepo.GetCompanies(); 29 | return Ok(companies); 30 | } 31 | catch (Exception ex) 32 | { 33 | //log error 34 | return StatusCode(500, ex.Message); 35 | } 36 | } 37 | 38 | [HttpGet("{id}", Name = "CompanyById")] 39 | public async Task GetCompany(int id) 40 | { 41 | try 42 | { 43 | var company = await _companyRepo.GetCompany(id); 44 | if (company == null) 45 | return NotFound(); 46 | 47 | return Ok(company); 48 | } 49 | catch (Exception ex) 50 | { 51 | //log error 52 | return StatusCode(500, ex.Message); 53 | } 54 | } 55 | 56 | [HttpPost] 57 | public async Task CreateCompany(CompanyForCreationDto company) 58 | { 59 | try 60 | { 61 | var createdCompany = await _companyRepo.CreateCompany(company); 62 | return CreatedAtRoute("CompanyById", new { id = createdCompany.Id }, createdCompany); 63 | } 64 | catch (Exception ex) 65 | { 66 | //log error 67 | return StatusCode(500, ex.Message); 68 | } 69 | } 70 | 71 | [HttpPut("{id}")] 72 | public async Task UpdateCompany(int id, CompanyForUpdateDto company) 73 | { 74 | try 75 | { 76 | var dbCompany = await _companyRepo.GetCompany(id); 77 | if (dbCompany == null) 78 | return NotFound(); 79 | 80 | await _companyRepo.UpdateCompany(id, company); 81 | return NoContent(); 82 | } 83 | catch (Exception ex) 84 | { 85 | //log error 86 | return StatusCode(500, ex.Message); 87 | } 88 | } 89 | 90 | [HttpDelete("{id}")] 91 | public async Task DeleteCompany(int id) 92 | { 93 | try 94 | { 95 | var dbCompany = await _companyRepo.GetCompany(id); 96 | if (dbCompany == null) 97 | return NotFound(); 98 | 99 | await _companyRepo.DeleteCompany(id); 100 | return NoContent(); 101 | } 102 | catch (Exception ex) 103 | { 104 | //log error 105 | return StatusCode(500, ex.Message); 106 | } 107 | } 108 | 109 | [HttpGet("ByEmployeeId/{id}")] 110 | public async Task GetCompanyForEmployee(int id) 111 | { 112 | try 113 | { 114 | var company = await _companyRepo.GetCompanyByEmployeeId(id); 115 | if (company == null) 116 | return NotFound(); 117 | 118 | return Ok(company); 119 | } 120 | catch (Exception ex) 121 | { 122 | //log error 123 | return StatusCode(500, ex.Message); 124 | } 125 | } 126 | 127 | [HttpGet("{id}/MultipleResult")] 128 | public async Task GetCompanyEmployeesMultipleResult(int id) 129 | { 130 | try 131 | { 132 | var company = await _companyRepo.GetCompanyEmployeesMultipleResults(id); 133 | if (company == null) 134 | return NotFound(); 135 | 136 | return Ok(company); 137 | } 138 | catch (Exception ex) 139 | { 140 | //log error 141 | return StatusCode(500, ex.Message); 142 | } 143 | } 144 | 145 | [HttpGet("MultipleMapping")] 146 | public async Task GetCompaniesEmployeesMultipleMapping() 147 | { 148 | try 149 | { 150 | var company = await _companyRepo.GetCompaniesEmployeesMultipleMapping(); 151 | 152 | return Ok(company); 153 | } 154 | catch (Exception ex) 155 | { 156 | //log error 157 | return StatusCode(500, ex.Message); 158 | } 159 | } 160 | 161 | [HttpPost("multiple")] 162 | public async Task CreateCompany(List companies) 163 | { 164 | try 165 | { 166 | await _companyRepo.CreateMultipleCompanies(companies); 167 | return StatusCode(201); 168 | } 169 | catch (Exception ex) 170 | { 171 | //log error 172 | return StatusCode(500, ex.Message); 173 | } 174 | } 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /DapperASPNetCore/DapperASPNetCore/DapperASPNetCore.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /DapperASPNetCore/DapperASPNetCore/Dto/CompanyForCreationDto.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace DapperASPNetCore.Dto 7 | { 8 | public class CompanyForCreationDto 9 | { 10 | public string Name { get; set; } 11 | public string Address { get; set; } 12 | public string Country { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /DapperASPNetCore/DapperASPNetCore/Dto/CompanyForUpdateDto.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace DapperASPNetCore.Dto 7 | { 8 | public class CompanyForUpdateDto 9 | { 10 | public string Name { get; set; } 11 | public string Address { get; set; } 12 | public string Country { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /DapperASPNetCore/DapperASPNetCore/Entities/Company.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace DapperASPNetCore.Entities 7 | { 8 | public class Company 9 | { 10 | public int Id { get; set; } 11 | public string Name { get; set; } 12 | public string Address { get; set; } 13 | public string Country { get; set; } 14 | 15 | public List Employees { get; set; } = new List(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /DapperASPNetCore/DapperASPNetCore/Entities/Employee.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace DapperASPNetCore.Entities 7 | { 8 | public class Employee 9 | { 10 | public int Id { get; set; } 11 | public string Name { get; set; } 12 | public int Age { get; set; } 13 | public string Position { get; set; } 14 | public int CompanyId { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /DapperASPNetCore/DapperASPNetCore/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Configuration; 3 | using Microsoft.Extensions.Hosting; 4 | using Microsoft.Extensions.Logging; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | 10 | namespace DapperASPNetCore 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IHostBuilder CreateHostBuilder(string[] args) => 20 | Host.CreateDefaultBuilder(args) 21 | .ConfigureWebHostDefaults(webBuilder => 22 | { 23 | webBuilder.UseStartup(); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /DapperASPNetCore/DapperASPNetCore/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "profiles": { 4 | "DapperASPNetCore": { 5 | "commandName": "Project", 6 | "dotnetRunMessages": "true", 7 | "launchBrowser": false, 8 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 9 | "environmentVariables": { 10 | "ASPNETCORE_ENVIRONMENT": "Development" 11 | } 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /DapperASPNetCore/DapperASPNetCore/Repository/CompanyRepository.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using DapperASPNetCore.Context; 3 | using DapperASPNetCore.Contracts; 4 | using DapperASPNetCore.Dto; 5 | using DapperASPNetCore.Entities; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Data; 9 | using System.Linq; 10 | using System.Threading.Tasks; 11 | 12 | namespace DapperASPNetCore.Repository 13 | { 14 | public class CompanyRepository : ICompanyRepository 15 | { 16 | private readonly DapperContext _context; 17 | 18 | public CompanyRepository(DapperContext context) 19 | { 20 | _context = context; 21 | } 22 | 23 | public async Task> GetCompanies() 24 | { 25 | var query = "SELECT Id, Name, Address, Country FROM Companies"; 26 | 27 | using (var connection = _context.CreateConnection()) 28 | { 29 | var companies = await connection.QueryAsync(query); 30 | return companies.ToList(); 31 | } 32 | } 33 | 34 | public async Task GetCompany(int id) 35 | { 36 | var query = "SELECT * FROM Companies WHERE Id = @Id"; 37 | 38 | using (var connection = _context.CreateConnection()) 39 | { 40 | var company = await connection.QuerySingleOrDefaultAsync(query, new { id }); 41 | 42 | return company; 43 | } 44 | } 45 | 46 | public async Task CreateCompany(CompanyForCreationDto company) 47 | { 48 | var query = "INSERT INTO Companies (Name, Address, Country) VALUES (@Name, @Address, @Country)" + 49 | "SELECT CAST(SCOPE_IDENTITY() as int)"; 50 | 51 | var parameters = new DynamicParameters(); 52 | parameters.Add("Name", company.Name, DbType.String); 53 | parameters.Add("Address", company.Address, DbType.String); 54 | parameters.Add("Country", company.Country, DbType.String); 55 | 56 | using (var connection = _context.CreateConnection()) 57 | { 58 | var id = await connection.QuerySingleAsync(query, parameters); 59 | 60 | var createdCompany = new Company 61 | { 62 | Id = id, 63 | Name = company.Name, 64 | Address = company.Address, 65 | Country = company.Country 66 | }; 67 | 68 | return createdCompany; 69 | } 70 | } 71 | 72 | public async Task UpdateCompany(int id, CompanyForUpdateDto company) 73 | { 74 | var query = "UPDATE Companies SET Name = @Name, Address = @Address, Country = @Country WHERE Id = @Id"; 75 | 76 | var parameters = new DynamicParameters(); 77 | parameters.Add("Id", id, DbType.Int32); 78 | parameters.Add("Name", company.Name, DbType.String); 79 | parameters.Add("Address", company.Address, DbType.String); 80 | parameters.Add("Country", company.Country, DbType.String); 81 | 82 | using (var connection = _context.CreateConnection()) 83 | { 84 | await connection.ExecuteAsync(query, parameters); 85 | } 86 | } 87 | 88 | public async Task DeleteCompany(int id) 89 | { 90 | var query = "DELETE FROM Companies WHERE Id = @Id"; 91 | 92 | using (var connection = _context.CreateConnection()) 93 | { 94 | await connection.ExecuteAsync(query, new { id }); 95 | } 96 | } 97 | 98 | public async Task GetCompanyByEmployeeId(int id) 99 | { 100 | var procedureName = "ShowCompanyForProvidedEmployeeId"; 101 | var parameters = new DynamicParameters(); 102 | parameters.Add("Id", id, DbType.Int32, ParameterDirection.Input); 103 | 104 | using (var connection = _context.CreateConnection()) 105 | { 106 | var company = await connection.QueryFirstOrDefaultAsync 107 | (procedureName, parameters, commandType: CommandType.StoredProcedure); 108 | 109 | return company; 110 | } 111 | } 112 | 113 | public async Task GetCompanyEmployeesMultipleResults(int id) 114 | { 115 | var query = "SELECT * FROM Companies WHERE Id = @Id;" + 116 | "SELECT * FROM Employees WHERE CompanyId = @Id"; 117 | 118 | using (var connection = _context.CreateConnection()) 119 | using (var multi = await connection.QueryMultipleAsync(query, new { id })) 120 | { 121 | var company = await multi.ReadSingleOrDefaultAsync(); 122 | if (company != null) 123 | company.Employees = (await multi.ReadAsync()).ToList(); 124 | 125 | return company; 126 | } 127 | } 128 | 129 | public async Task> GetCompaniesEmployeesMultipleMapping() 130 | { 131 | var query = "SELECT * FROM Companies c JOIN Employees e ON c.Id = e.CompanyId"; 132 | 133 | using (var connection = _context.CreateConnection()) 134 | { 135 | var companyDict = new Dictionary(); 136 | 137 | var companies = await connection.QueryAsync( 138 | query, (company, employee) => 139 | { 140 | if (!companyDict.TryGetValue(company.Id, out var currentCompany)) 141 | { 142 | currentCompany = company; 143 | companyDict.Add(currentCompany.Id, currentCompany); 144 | } 145 | 146 | currentCompany.Employees.Add(employee); 147 | return currentCompany; 148 | } 149 | ); 150 | 151 | return companies.Distinct().ToList(); 152 | } 153 | } 154 | 155 | public async Task CreateMultipleCompanies(List companies) 156 | { 157 | var query = "INSERT INTO Companies (Name, Address, Country) VALUES (@Name, @Address, @Country)"; 158 | 159 | using (var connection = _context.CreateConnection()) 160 | { 161 | connection.Open(); 162 | 163 | using (var transaction = connection.BeginTransaction()) 164 | { 165 | foreach (var company in companies) 166 | { 167 | var parameters = new DynamicParameters(); 168 | parameters.Add("Name", company.Name, DbType.String); 169 | parameters.Add("Address", company.Address, DbType.String); 170 | parameters.Add("Country", company.Country, DbType.String); 171 | 172 | await connection.ExecuteAsync(query, parameters, transaction: transaction); 173 | //throw new Exception(); 174 | } 175 | 176 | transaction.Commit(); 177 | } 178 | } 179 | } 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /DapperASPNetCore/DapperASPNetCore/Startup.cs: -------------------------------------------------------------------------------- 1 | using DapperASPNetCore.Context; 2 | using DapperASPNetCore.Contracts; 3 | using DapperASPNetCore.Repository; 4 | using Microsoft.AspNetCore.Builder; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.DependencyInjection; 8 | using Microsoft.Extensions.Hosting; 9 | 10 | namespace DapperASPNetCore 11 | { 12 | public class Startup 13 | { 14 | public Startup(IConfiguration configuration) 15 | { 16 | Configuration = configuration; 17 | } 18 | 19 | public IConfiguration Configuration { get; } 20 | 21 | public void ConfigureServices(IServiceCollection services) 22 | { 23 | services.AddSingleton(); 24 | services.AddScoped(); 25 | services.AddControllers(); 26 | } 27 | 28 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 29 | { 30 | if (env.IsDevelopment()) 31 | { 32 | app.UseDeveloperExceptionPage(); 33 | } 34 | 35 | app.UseHttpsRedirection(); 36 | 37 | app.UseRouting(); 38 | 39 | app.UseAuthorization(); 40 | 41 | app.UseEndpoints(endpoints => 42 | { 43 | endpoints.MapControllers(); 44 | }); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /DapperASPNetCore/DapperASPNetCore/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /DapperASPNetCore/DapperASPNetCore/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "ConnectionStrings": { 10 | "SqlConnection": "server=.; database=DapperASPNetCore; Integrated Security=true" 11 | }, 12 | "AllowedHosts": "*" 13 | } 14 | -------------------------------------------------------------------------------- /Initial Script with Data.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CodeMazeBlog/dapper-aspnetcore-webapi/e73a1bcd23b6ff5de89f9f743eaf2329f745434c/Initial Script with Data.sql -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Code Maze 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 | # Using Dapper with ASP.NET Core Web API 2 | ## https://code-maze.com/using-dapper-with-asp-net-core-web-api 3 | This repo contains the source code for the "Using Dapper with ASP.NET Core Web API" article on Code Maze 4 | --------------------------------------------------------------------------------