├── .gitignore ├── EFCoreRepositoryUnitofWork.sln ├── README.md └── src └── EFCoreRepositoryUnitofWork ├── Controllers ├── CommentController.cs ├── PostController.cs └── UserController.cs ├── DependencyInjection.cs ├── EFCoreRepositoryUnitofWork.csproj ├── Entities ├── Comment.cs ├── Common │ ├── Entity.cs │ └── ValueObject.cs ├── Post.cs ├── User.cs └── ValueObject │ └── Address.cs ├── Interfaces ├── IApplicationContext.cs ├── ICustomPostRepository.cs ├── IReadRepository.cs ├── IReadRepositoryBase.cs ├── IRepository.cs ├── IRepositoryBase.cs └── IUnitOfWork.cs ├── Persistence ├── ApplicationContext.cs ├── ApplicationContextSeed.cs ├── Configurations │ ├── CommentConfiguration.cs │ ├── PostConfiguration.cs │ └── UserConfiguration.cs └── Repositories │ ├── BaseRepository.cs │ └── CustomPostRepository.cs ├── Program.cs ├── Properties └── launchSettings.json ├── appsettings.Development.json ├── appsettings.json └── wwwroot └── swagger-ui └── custom.css /.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 | -------------------------------------------------------------------------------- /EFCoreRepositoryUnitofWork.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.1.32319.34 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EFCoreRepositoryUnitofWork", "src\EFCoreRepositoryUnitofWork\EFCoreRepositoryUnitofWork.csproj", "{00BE5318-428B-4A44-A0C2-F7CC3E6F6961}" 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 | {00BE5318-428B-4A44-A0C2-F7CC3E6F6961}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {00BE5318-428B-4A44-A0C2-F7CC3E6F6961}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {00BE5318-428B-4A44-A0C2-F7CC3E6F6961}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {00BE5318-428B-4A44-A0C2-F7CC3E6F6961}.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 = {8D4259EE-4694-4260-AD01-A7A82570ACA0} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Repository Pattern & Unit of Work – Entity Framework Core and .NET 2 | In this repository, you will find a demo of the Repository pattern and the Unit of Work pattern with Entity Framework Core and .NET 3 | 4 | ## Technologies 5 | 6 | * [NET 6](https://dotnet.microsoft.com/es-es/download/dotnet/6.0) 7 | * [Entity Framework Core](https://learn.microsoft.com/es-es/ef/core/what-is-new/ef-core-6.0/whatsnew) 8 | 9 | ## Versions 10 | The main branch is now on .NET 6.0. 11 | 12 | ## Learn more 13 | [Repository Pattern & Unit of Work – Entity Framework Core and .NET 6](https://arbems.com/en/repository-pattern-unit-of-work-in-ef-core) 14 | -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Controllers/CommentController.cs: -------------------------------------------------------------------------------- 1 | using EFCoreRepositoryUnitofWork.Entities; 2 | using EFCoreRepositoryUnitofWork.Interfaces; 3 | using Microsoft.AspNetCore.JsonPatch; 4 | using Microsoft.AspNetCore.Mvc; 5 | using Microsoft.EntityFrameworkCore; 6 | 7 | namespace EFCoreRepositoryUnitofWork.Controllers; 8 | 9 | [ApiController] 10 | [Route("[Controller]")] 11 | public class CommentController : ControllerBase 12 | { 13 | private readonly IRepository _commentRepository; 14 | 15 | public CommentController(IRepository commentRepository) 16 | { 17 | _commentRepository = commentRepository; 18 | } 19 | 20 | [HttpGet] 21 | public ActionResult Get() 22 | { 23 | var results = _commentRepository.GetAll(); 24 | 25 | return Ok(results); 26 | } 27 | 28 | [HttpGet("{id:int}")] 29 | public async Task Get(int id) 30 | { 31 | var entity = await _commentRepository.GetByIdAsync(id); 32 | 33 | if (entity is null) 34 | return NotFound($"Entity with Id = {id} not found."); 35 | 36 | return Ok(entity); 37 | } 38 | 39 | [HttpPost] 40 | public async Task> Comment([FromForm] Comment entity) 41 | { 42 | if (entity is null) 43 | return BadRequest(ModelState); 44 | 45 | _commentRepository.Add(entity); 46 | 47 | var result = await _commentRepository.UnitOfWork.SaveChangesAsync(); 48 | if (result <= 0) 49 | return BadRequest("Your changes have no[t been saved."); 50 | 51 | return CreatedAtAction(nameof(Get), new { id = entity.Id }, entity); 52 | } 53 | 54 | [HttpPut("{id:int}")] 55 | public async Task Put(int id, [FromBody] Comment entity) 56 | { 57 | if (entity is null) 58 | return BadRequest(ModelState); 59 | 60 | if (id != entity.Id) 61 | return BadRequest("Identifier is not valid or Identifiers don't match."); 62 | 63 | var existEntity = await _commentRepository.GetByIdAsync(id); 64 | 65 | if (existEntity is null) 66 | return NotFound($"Entity with Id = {id} not found."); 67 | 68 | var result = await _commentRepository.UnitOfWork.SaveChangesAsync(); 69 | if (result <= 0) 70 | return BadRequest("Your changes have not been saved."); 71 | 72 | return NoContent(); 73 | } 74 | 75 | [HttpPatch("{id:int}")] 76 | public async Task Patch(int id, [FromBody] JsonPatchDocument patchDoc) 77 | { 78 | if (patchDoc is null) 79 | return BadRequest(ModelState); 80 | 81 | var existEntity = await _commentRepository.GetByIdAsync(id); 82 | if (existEntity is null) 83 | return NotFound($"Entity with Id = {id} not found"); 84 | 85 | patchDoc.ApplyTo(existEntity, ModelState); 86 | 87 | var isValid = TryValidateModel(existEntity); 88 | if (!isValid) 89 | return BadRequest(ModelState); 90 | 91 | try 92 | { 93 | await _commentRepository.UnitOfWork.SaveChangesAsync(); 94 | } 95 | catch (DbUpdateConcurrencyException) 96 | { 97 | throw; 98 | } 99 | 100 | return NoContent(); 101 | } 102 | 103 | [HttpDelete("{id}")] 104 | public async Task Delete(int id) 105 | { 106 | var entity = await _commentRepository.GetByIdAsync(id); 107 | 108 | if (entity is null) 109 | return NotFound($"Entity with Id = {id} not found"); 110 | 111 | _commentRepository.Delete(entity); 112 | 113 | var result = await _commentRepository.UnitOfWork.SaveChangesAsync(); 114 | if (result <= 0) 115 | return BadRequest(); 116 | 117 | return NoContent(); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Controllers/PostController.cs: -------------------------------------------------------------------------------- 1 | using EFCoreRepositoryUnitofWork.Entities; 2 | using EFCoreRepositoryUnitofWork.Interfaces; 3 | using Microsoft.AspNetCore.JsonPatch; 4 | using Microsoft.AspNetCore.Mvc; 5 | using Microsoft.EntityFrameworkCore; 6 | 7 | namespace EFCoreRepositoryUnitofWork.Controllers; 8 | 9 | [ApiController] 10 | [Route("[Controller]")] 11 | public class PostController : ControllerBase 12 | { 13 | private readonly ICustomPostRepository _postCustomRepository; 14 | 15 | public PostController(ICustomPostRepository postCustomRepository) 16 | { 17 | _postCustomRepository = postCustomRepository; 18 | } 19 | 20 | [HttpGet] 21 | public ActionResult Get() 22 | { 23 | var results = _postCustomRepository.GetAll(); 24 | 25 | return Ok(results); 26 | } 27 | 28 | [HttpGet("{id:int}")] 29 | public async Task Get(int id) 30 | { 31 | var entity = await _postCustomRepository.GetByIdAsync(id); 32 | 33 | if (entity is null) 34 | return NotFound($"Entity with Id = {id} not found."); 35 | 36 | return Ok(entity); 37 | } 38 | 39 | [HttpGet("{id:int}/comments")] 40 | public async Task GetWithComments(int id) 41 | { 42 | var entity = await _postCustomRepository.GetPostWithCommentsAsync(id); 43 | 44 | if (entity is null) 45 | return NotFound($"Entity with Id = {id} not found."); 46 | 47 | return Ok(entity); 48 | } 49 | 50 | [HttpGet("{id:int}/WithMoreComments")] 51 | public async Task GetPostWithMoreComments(int id) 52 | { 53 | var entity = await _postCustomRepository.GetByIdAsync(id); 54 | 55 | if (entity is null) 56 | return NotFound($"Entity with Id = {id} not found."); 57 | 58 | return Ok(entity); 59 | } 60 | 61 | [HttpPost] 62 | public async Task> Post([FromForm] Post entity) 63 | { 64 | if (entity is null) 65 | return BadRequest(ModelState); 66 | 67 | _postCustomRepository.Add(entity); 68 | 69 | var result = await _postCustomRepository.UnitOfWork.SaveChangesAsync(); 70 | if (result <= 0) 71 | return BadRequest("Your changes have no[t been saved."); 72 | 73 | return CreatedAtAction(nameof(Get), new { id = entity.Id }, entity); 74 | } 75 | 76 | [HttpPut("{id:int}")] 77 | public async Task Put(int id, [FromBody] Post entity) 78 | { 79 | if (entity is null) 80 | return BadRequest(ModelState); 81 | 82 | if (id != entity.Id) 83 | return BadRequest("Identifier is not valid or Identifiers don't match."); 84 | 85 | var existEntity = await _postCustomRepository.GetByIdAsync(id); 86 | 87 | if (existEntity is null) 88 | return NotFound($"Entity with Id = {id} not found."); 89 | 90 | var result = await _postCustomRepository.UnitOfWork.SaveChangesAsync(); 91 | if (result <= 0) 92 | return BadRequest("Your changes have not been saved."); 93 | 94 | return NoContent(); 95 | } 96 | 97 | [HttpPatch("{id:int}")] 98 | public async Task Patch(int id, [FromBody] JsonPatchDocument patchDoc) 99 | { 100 | if (patchDoc is null) 101 | return BadRequest(ModelState); 102 | 103 | var existEntity = await _postCustomRepository.GetByIdAsync(id); 104 | if (existEntity is null) 105 | return NotFound($"Entity with Id = {id} not found"); 106 | 107 | patchDoc.ApplyTo(existEntity, ModelState); 108 | 109 | var isValid = TryValidateModel(existEntity); 110 | if (!isValid) 111 | return BadRequest(ModelState); 112 | 113 | try 114 | { 115 | await _postCustomRepository.UnitOfWork.SaveChangesAsync(); 116 | } 117 | catch (DbUpdateConcurrencyException) 118 | { 119 | throw; 120 | } 121 | 122 | return NoContent(); 123 | } 124 | 125 | [HttpDelete("{id}")] 126 | public async Task Delete(int id) 127 | { 128 | var entity = await _postCustomRepository.GetByIdAsync(id); 129 | 130 | if (entity is null) 131 | return NotFound($"Entity with Id = {id} not found"); 132 | 133 | _postCustomRepository.Delete(entity); 134 | 135 | var result = await _postCustomRepository.UnitOfWork.SaveChangesAsync(); 136 | if (result <= 0) 137 | return BadRequest(); 138 | 139 | return NoContent(); 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Controllers/UserController.cs: -------------------------------------------------------------------------------- 1 | using EFCoreRepositoryUnitofWork.Entities; 2 | using EFCoreRepositoryUnitofWork.Interfaces; 3 | using Microsoft.AspNetCore.Mvc; 4 | using Microsoft.EntityFrameworkCore; 5 | 6 | namespace EFCoreRepositoryUnitofWork.Controllers; 7 | 8 | [ApiController] 9 | [Route("[Controller]")] 10 | public class UserController : ControllerBase 11 | { 12 | private readonly IReadRepository _userReadRepository; 13 | 14 | public UserController(IReadRepository userReadRepository) 15 | { 16 | _userReadRepository = userReadRepository; 17 | } 18 | 19 | [HttpGet] 20 | public ActionResult Get() 21 | { 22 | var results = _userReadRepository.GetAll(); 23 | 24 | return Ok(results); 25 | } 26 | 27 | [HttpGet("{id:int}")] 28 | public async Task Get(int id) 29 | { 30 | var entity = await _userReadRepository.GetByIdAsync(id); 31 | 32 | if (entity is null) 33 | return NotFound($"Entity with Id = {id} not found."); 34 | 35 | return Ok(entity); 36 | } 37 | 38 | [HttpGet("{id:int}/posts")] 39 | public async Task GetUserWithPosts(int id) 40 | { 41 | var entity = await _userReadRepository.GetAllIncluding(a => a.Posts).FirstOrDefaultAsync(a => a.Id == id); 42 | 43 | if (entity is null) 44 | return NotFound($"Entity with Id = {id} not found."); 45 | 46 | return Ok(entity); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/DependencyInjection.cs: -------------------------------------------------------------------------------- 1 | using EFCoreRepositoryUnitofWork.Interfaces; 2 | using EFCoreRepositoryUnitofWork.Persistence; 3 | using EFCoreRepositoryUnitofWork.Persistence.Repositories; 4 | using Microsoft.EntityFrameworkCore; 5 | 6 | namespace Infrastructure; 7 | 8 | public static class DependencyInjection 9 | { 10 | public static IServiceCollection AddDependencyInjection(this IServiceCollection services, IConfiguration configuration) 11 | { 12 | if (configuration.GetValue("UseInMemoryDatabase")) 13 | { 14 | services.AddDbContext(options => 15 | options.UseInMemoryDatabase("InMemoryDb")); 16 | } 17 | else 18 | { 19 | services.AddDbContext(options => 20 | options.UseSqlServer( 21 | configuration.GetConnectionString("DefaultConnection"), 22 | b => b.MigrationsAssembly(typeof(ApplicationContext).Assembly.FullName))); 23 | } 24 | 25 | services.AddScoped(provider => provider.GetRequiredService()); 26 | 27 | services.AddTransient(typeof(IRepository<>), typeof(BaseRepository<>)); 28 | services.AddTransient(typeof(IReadRepository<>), typeof(BaseRepository<>)); 29 | services.AddTransient(); 30 | 31 | return services; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/EFCoreRepositoryUnitofWork.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Entities/Comment.cs: -------------------------------------------------------------------------------- 1 | using EFCoreRepositoryUnitofWork.Common; 2 | 3 | namespace EFCoreRepositoryUnitofWork.Entities; 4 | 5 | public class Comment : Entity 6 | { 7 | public int PostId { get; set; } 8 | public string Name { get; set; } 9 | public string Email { get; set; } 10 | public string Body { get; set; } 11 | } 12 | -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Entities/Common/Entity.cs: -------------------------------------------------------------------------------- 1 | namespace EFCoreRepositoryUnitofWork.Common; 2 | 3 | public abstract class Entity 4 | { 5 | public int Id { get; set; } 6 | 7 | /* auditable fields */ 8 | public DateTime? Created { get; set; } 9 | 10 | public string? CreatedBy { get; set; } 11 | 12 | public DateTime? LastModified { get; set; } 13 | 14 | public string? LastModifiedBy { get; set; } 15 | } 16 | -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Entities/Common/ValueObject.cs: -------------------------------------------------------------------------------- 1 | namespace EFCoreRepositoryUnitofWork.Common; 2 | 3 | // Learn more: https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/implement-value-objects 4 | public abstract class ValueObject 5 | { 6 | protected static bool EqualOperator(ValueObject left, ValueObject right) 7 | { 8 | if (left is null ^ right is null) 9 | { 10 | return false; 11 | } 12 | 13 | return left?.Equals(right!) != false; 14 | } 15 | 16 | protected static bool NotEqualOperator(ValueObject left, ValueObject right) 17 | { 18 | return !EqualOperator(left, right); 19 | } 20 | 21 | protected abstract IEnumerable GetEqualityComponents(); 22 | 23 | public override bool Equals(object? obj) 24 | { 25 | if (obj == null || obj.GetType() != GetType()) 26 | { 27 | return false; 28 | } 29 | 30 | var other = (ValueObject)obj; 31 | return GetEqualityComponents().SequenceEqual(other.GetEqualityComponents()); 32 | } 33 | 34 | public override int GetHashCode() 35 | { 36 | return GetEqualityComponents() 37 | .Select(x => x != null ? x.GetHashCode() : 0) 38 | .Aggregate((x, y) => x ^ y); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Entities/Post.cs: -------------------------------------------------------------------------------- 1 | using EFCoreRepositoryUnitofWork.Common; 2 | 3 | namespace EFCoreRepositoryUnitofWork.Entities; 4 | 5 | public class Post : Entity 6 | { 7 | public int UserId { get; set; } 8 | public string Title { get; set; } 9 | public string Body { get; set; } 10 | 11 | private List _comments = new(); 12 | public ICollection Comments => _comments; 13 | } 14 | -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Entities/User.cs: -------------------------------------------------------------------------------- 1 | using EFCoreRepositoryUnitofWork.Common; 2 | 3 | namespace EFCoreRepositoryUnitofWork.Entities; 4 | 5 | public class User : Entity 6 | { 7 | public string Name { get; set; } 8 | 9 | public string Username { get; set; } 10 | 11 | public string Email { get; set; } 12 | 13 | public Address Address { get; set; } 14 | 15 | private List _posts = new(); 16 | public ICollection Posts => _posts; 17 | } 18 | -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Entities/ValueObject/Address.cs: -------------------------------------------------------------------------------- 1 | using EFCoreRepositoryUnitofWork.Common; 2 | 3 | namespace EFCoreRepositoryUnitofWork.Entities; 4 | 5 | public class Address : ValueObject 6 | { 7 | public String Street { get; private set; } 8 | public String City { get; private set; } 9 | public String State { get; private set; } 10 | public String Country { get; private set; } 11 | public String ZipCode { get; private set; } 12 | 13 | public Address() { } 14 | 15 | public Address(string street, string city, string state, string country, string zipcode) 16 | { 17 | Street = street; 18 | City = city; 19 | State = state; 20 | Country = country; 21 | ZipCode = zipcode; 22 | } 23 | 24 | protected override IEnumerable GetEqualityComponents() 25 | { 26 | // Using a yield return statement to return each element one at a time 27 | yield return Street; 28 | yield return City; 29 | yield return State; 30 | yield return Country; 31 | yield return ZipCode; 32 | } 33 | } -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Interfaces/IApplicationContext.cs: -------------------------------------------------------------------------------- 1 | using EFCoreRepositoryUnitofWork.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | 4 | namespace EFCoreRepositoryUnitofWork.Interfaces; 5 | 6 | public interface IApplicationContext : IUnitOfWork 7 | { 8 | DbSet Users { get; } 9 | DbSet Posts { get; } 10 | DbSet Comments { get; } 11 | } -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Interfaces/ICustomPostRepository.cs: -------------------------------------------------------------------------------- 1 | using EFCoreRepositoryUnitofWork.Entities; 2 | 3 | namespace EFCoreRepositoryUnitofWork.Interfaces; 4 | 5 | public interface ICustomPostRepository : IRepository, IReadRepository 6 | { 7 | new Post Add(Post entity); 8 | 9 | Task GetPostWithCommentsAsync(int id); 10 | 11 | IEnumerable GetPostWithMoreComments(int count); 12 | } -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Interfaces/IReadRepository.cs: -------------------------------------------------------------------------------- 1 | namespace EFCoreRepositoryUnitofWork.Interfaces; 2 | 3 | public interface IReadRepository : IReadRepositoryBase where TEntity : class { } -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Interfaces/IReadRepositoryBase.cs: -------------------------------------------------------------------------------- 1 | using System.Linq.Expressions; 2 | 3 | namespace EFCoreRepositoryUnitofWork.Interfaces; 4 | 5 | public interface IReadRepositoryBase where TEntity : class 6 | { 7 | IQueryable GetAll(bool asNoTracking = true); 8 | IQueryable GetAllBySpec(Expression> predicate, bool asNoTracking = true); 9 | Task GetByIdAsync(TId id, CancellationToken cancellationToken = default) where TId : notnull; 10 | Task GetBySpecAsync(Expression> predicate, CancellationToken cancellationToken = default); 11 | Task> ListAsync(CancellationToken cancellationToken = default); 12 | Task> ListAsync(Expression> predicate, CancellationToken cancellationToken = default); 13 | Task CountAsync(CancellationToken cancellationToken = default); 14 | Task CountAsync(Expression> predicate, CancellationToken cancellationToken = default); 15 | Task AnyAsync(CancellationToken cancellationToken = default); 16 | Task AnyAsync(Expression> predicate, CancellationToken cancellationToken = default); 17 | IQueryable GetAllIncluding(params Expression>[] includeProperties); 18 | } -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Interfaces/IRepository.cs: -------------------------------------------------------------------------------- 1 | namespace EFCoreRepositoryUnitofWork.Interfaces; 2 | 3 | public interface IRepository : IRepositoryBase where TEntity : class { } -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Interfaces/IRepositoryBase.cs: -------------------------------------------------------------------------------- 1 | namespace EFCoreRepositoryUnitofWork.Interfaces; 2 | 3 | public interface IRepositoryBase : IReadRepositoryBase where TEntity : class 4 | { 5 | IUnitOfWork UnitOfWork { get; } 6 | 7 | TEntity Add(TEntity entity); 8 | Task AddAsync(TEntity entity, CancellationToken cancellationToken = default); 9 | ICollection AddRange(ICollection entities); 10 | Task AddRangeAsync(ICollection entities, CancellationToken cancellationToken = default); 11 | void Delete(TEntity entity); 12 | Task DeleteAsync(TEntity entity, CancellationToken cancellationToken = default); 13 | void DeleteRange(ICollection entities); 14 | Task DeleteRangeAsync(ICollection entities, CancellationToken cancellationToken = default); 15 | void Update(TEntity entity); 16 | Task UpdateAsync(TEntity entity, CancellationToken cancellationToken = default); 17 | } -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Interfaces/IUnitOfWork.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Storage; 2 | 3 | namespace EFCoreRepositoryUnitofWork.Interfaces; 4 | 5 | public interface IUnitOfWork : IDisposable 6 | { 7 | Task SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken)); 8 | bool HasActiveTransaction { get; } 9 | IDbContextTransaction GetCurrentTransaction(); 10 | Task BeginTransactionAsync(); 11 | Task CommitAsync(IDbContextTransaction transaction); 12 | } -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Persistence/ApplicationContext.cs: -------------------------------------------------------------------------------- 1 | using EFCoreRepositoryUnitofWork.Entities; 2 | using EFCoreRepositoryUnitofWork.Interfaces; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Storage; 5 | using System.Reflection; 6 | 7 | namespace EFCoreRepositoryUnitofWork.Persistence; 8 | 9 | public class ApplicationContext : DbContext, IApplicationContext 10 | { 11 | public DbSet Users => Set(); 12 | public DbSet Posts => Set(); 13 | public DbSet Comments => Set(); 14 | 15 | public ApplicationContext(DbContextOptions options) : base(options) { } 16 | 17 | protected override void OnModelCreating(ModelBuilder builder) 18 | { 19 | builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly()); 20 | 21 | base.OnModelCreating(builder); 22 | } 23 | 24 | public override async Task SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) 25 | { 26 | var result = await base.SaveChangesAsync(cancellationToken); 27 | 28 | return result; 29 | } 30 | 31 | private IDbContextTransaction _currentTransaction; 32 | public IDbContextTransaction GetCurrentTransaction() => _currentTransaction; 33 | public bool HasActiveTransaction => _currentTransaction != null; 34 | 35 | public async Task BeginTransactionAsync() 36 | { 37 | if (_currentTransaction != null) return null!; 38 | 39 | _currentTransaction = await Database.BeginTransactionAsync(); 40 | 41 | return _currentTransaction; 42 | } 43 | 44 | public async Task CommitAsync(IDbContextTransaction transaction) 45 | { 46 | if (transaction == null) throw new ArgumentNullException(nameof(transaction)); 47 | if (transaction != _currentTransaction) throw new InvalidOperationException($"Transaction {transaction.TransactionId} is not current"); 48 | 49 | try 50 | { 51 | await SaveChangesAsync(); 52 | transaction.Commit(); 53 | } 54 | catch 55 | { 56 | RollbackTransaction(); 57 | throw; 58 | } 59 | finally 60 | { 61 | if (_currentTransaction != null) 62 | { 63 | _currentTransaction.Dispose(); 64 | _currentTransaction = null!; 65 | } 66 | } 67 | } 68 | 69 | private void RollbackTransaction() 70 | { 71 | try 72 | { 73 | _currentTransaction?.Rollback(); 74 | } 75 | finally 76 | { 77 | if (_currentTransaction != null) 78 | { 79 | _currentTransaction.Dispose(); 80 | _currentTransaction = null!; 81 | } 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Persistence/ApplicationContextSeed.cs: -------------------------------------------------------------------------------- 1 | using EFCoreRepositoryUnitofWork.Entities; 2 | 3 | namespace EFCoreRepositoryUnitofWork.Persistence; 4 | 5 | public static class ApplicationContextSeed 6 | { 7 | public static async Task SeedSampleDataAsync(ApplicationContext context) 8 | { 9 | // Seed, if necessary 10 | if (!context.Users.Any()) 11 | { 12 | var user = new User 13 | { 14 | Id = 1, 15 | Name = "Alberto", 16 | Email = "contacto@arbems.com", 17 | Username = "arbems", 18 | Address = new Address("Calle sierpes", "Sevilla", "Sevilla", "España", "41005"), 19 | Posts = 20 | { 21 | new Post { Id = 1, 22 | Title = "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", 23 | Body = "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto", 24 | UserId = 1, 25 | Comments = { 26 | new Comment { Id = 1, Name = "Oscar", Body = "id labore ex et quam laborum", Email = "Lew@alysha.tv", PostId = 1}, 27 | new Comment { Id = 2, Name = "Jesus", Body = "odio adipisci rerum aut animi", Email = "Hayden@althea.biz", PostId = 1}, 28 | new Comment { Id = 3, Name = "Marta", Body = "vero eaque aliquid doloribus et culpa", Email = "Presley.Mueller@myrl.com", PostId = 1}, 29 | } 30 | }, 31 | new Post { Id = 2, 32 | Title = "qui est esse", 33 | Body = "st rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus ", 34 | UserId = 1, 35 | Comments = { 36 | new Comment { Id = 4, Name = "Ana", Body = "et fugit eligendi deleniti quidem qui sint nihil autem", Email = "Dallas@ole.me", PostId = 2}, 37 | } 38 | }, 39 | new Post { Id = 3, 40 | Title = "ea molestias quasi exercitationem repellat qui ipsa sit aut", 41 | Body = "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut", 42 | UserId = 1, 43 | Comments = { 44 | new Comment { Id = 5, Name = "Elena", Body = "et omnis dolorem", Email = "Mallory_Kunze@marie.org", PostId = 3}, 45 | new Comment { Id = 6, Name = "Carlos", Body = "provident id voluptas", Email = "Meghan_Littel@rene.us", PostId = 3}, 46 | } 47 | } 48 | } 49 | }; 50 | 51 | context.Users.Add(user); 52 | 53 | await context.SaveChangesAsync(); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Persistence/Configurations/CommentConfiguration.cs: -------------------------------------------------------------------------------- 1 | using EFCoreRepositoryUnitofWork.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 4 | 5 | namespace EFCoreRepositoryUnitofWork.Persistence.Configurations; 6 | 7 | public class CommentConfiguration : IEntityTypeConfiguration 8 | { 9 | public void Configure(EntityTypeBuilder builder) 10 | { 11 | builder.HasKey(t => t.Id); 12 | 13 | builder.Property(t => t.Name) 14 | .HasMaxLength(100) 15 | .IsRequired(); 16 | 17 | builder.Property(t => t.Body) 18 | .HasMaxLength(1000) 19 | .IsRequired(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Persistence/Configurations/PostConfiguration.cs: -------------------------------------------------------------------------------- 1 | using EFCoreRepositoryUnitofWork.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 4 | 5 | namespace EFCoreRepositoryUnitofWork.Persistence.Configurations; 6 | 7 | public class PostConfiguration : IEntityTypeConfiguration 8 | { 9 | public void Configure(EntityTypeBuilder builder) 10 | { 11 | builder.HasKey(t => t.Id); 12 | 13 | builder.Property(t => t.Title) 14 | .HasMaxLength(200) 15 | .IsRequired(); 16 | 17 | builder.Property(t => t.Body) 18 | .HasMaxLength(4000) 19 | .IsRequired(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Persistence/Configurations/UserConfiguration.cs: -------------------------------------------------------------------------------- 1 | using EFCoreRepositoryUnitofWork.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 4 | 5 | namespace EFCoreRepositoryUnitofWork.Persistence.Configurations; 6 | 7 | public class UserConfiguration : IEntityTypeConfiguration 8 | { 9 | public void Configure(EntityTypeBuilder builder) 10 | { 11 | builder.HasKey(t => t.Id); 12 | 13 | builder.Property(t => t.Username) 14 | .HasMaxLength(100) 15 | .IsRequired(); 16 | 17 | builder 18 | .OwnsOne(b => b.Address); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Persistence/Repositories/BaseRepository.cs: -------------------------------------------------------------------------------- 1 | using EFCoreRepositoryUnitofWork.Interfaces; 2 | using Microsoft.EntityFrameworkCore; 3 | using System.Linq.Expressions; 4 | 5 | namespace EFCoreRepositoryUnitofWork.Persistence.Repositories; 6 | 7 | public class BaseRepository : IRepository, IReadRepository where TEntity : class 8 | { 9 | private readonly ApplicationContext _context; 10 | public IUnitOfWork UnitOfWork 11 | { 12 | get 13 | { 14 | return _context; 15 | } 16 | } 17 | 18 | public BaseRepository(ApplicationContext context) 19 | { 20 | _context = context ?? throw new ArgumentNullException(nameof(context)); 21 | } 22 | 23 | public virtual IQueryable GetAll(bool asNoTracking = true) 24 | { 25 | if (asNoTracking) 26 | return _context.Set().AsNoTracking(); 27 | else 28 | return _context.Set().AsQueryable(); 29 | } 30 | 31 | public virtual IQueryable GetAllBySpec(Expression> predicate, bool asNoTracking = true) 32 | { 33 | if (asNoTracking) 34 | return _context.Set().Where(predicate).AsNoTracking(); 35 | else 36 | return _context.Set().Where(predicate).AsQueryable(); 37 | } 38 | 39 | public virtual async Task GetByIdAsync(TId id, CancellationToken cancellationToken = default) where TId : notnull 40 | { 41 | return await _context.Set().FindAsync(new object[] { id }, cancellationToken: cancellationToken); 42 | } 43 | 44 | public virtual async Task GetBySpecAsync(Expression> predicate, CancellationToken cancellationToken = default) 45 | { 46 | return await _context.Set().FirstOrDefaultAsync(predicate, cancellationToken); 47 | } 48 | 49 | public virtual async Task> ListAsync(Expression> predicate, CancellationToken cancellationToken = default) 50 | { 51 | return await _context.Set().Where(predicate).ToListAsync(cancellationToken); 52 | } 53 | 54 | public virtual async Task> ListAsync(CancellationToken cancellationToken = default) 55 | { 56 | return await _context.Set().ToListAsync(cancellationToken); 57 | } 58 | 59 | public virtual async Task CountAsync(CancellationToken cancellationToken = default) 60 | { 61 | return await _context.Set().CountAsync(cancellationToken); 62 | } 63 | 64 | public virtual async Task CountAsync(Expression> predicate, CancellationToken cancellationToken = default) 65 | { 66 | return await _context.Set().Where(predicate).CountAsync(cancellationToken); 67 | } 68 | 69 | public virtual async Task AnyAsync(Expression> predicate, CancellationToken cancellationToken = default) 70 | { 71 | return await _context.Set().AnyAsync(predicate, cancellationToken); 72 | } 73 | 74 | public virtual async Task AnyAsync(CancellationToken cancellationToken = default) 75 | { 76 | return await _context.Set().AnyAsync(cancellationToken); 77 | } 78 | 79 | public virtual IQueryable GetAllIncluding(params Expression>[] includeProperties) 80 | { 81 | IQueryable queryable = GetAll(); 82 | foreach (Expression> includeProperty in includeProperties) 83 | { 84 | queryable = queryable.Include(includeProperty); 85 | } 86 | 87 | return queryable; 88 | } 89 | 90 | 91 | public virtual TEntity Add(TEntity entity) 92 | { 93 | return _context.Set().Add(entity).Entity; 94 | } 95 | 96 | public virtual async Task AddAsync(TEntity entity, CancellationToken cancellationToken = default) 97 | { 98 | _context.Set().Add(entity); 99 | 100 | await _context.SaveChangesAsync(cancellationToken); 101 | 102 | return entity; 103 | } 104 | 105 | public virtual ICollection AddRange(ICollection entities) 106 | { 107 | _context.Set().AddRange(entities); 108 | 109 | return entities; 110 | } 111 | 112 | public virtual async Task AddRangeAsync(ICollection entities, CancellationToken cancellationToken = default) 113 | { 114 | await _context.Set().AddRangeAsync(entities); 115 | 116 | return await _context.SaveChangesAsync(cancellationToken); 117 | } 118 | 119 | public virtual void Delete(TEntity entity) 120 | { 121 | _context.Set().Remove(entity); 122 | } 123 | 124 | public virtual async Task DeleteAsync(TEntity entity, CancellationToken cancellationToken = default) 125 | { 126 | _context.Set().Remove(entity); 127 | 128 | return await _context.SaveChangesAsync(cancellationToken); 129 | } 130 | 131 | public virtual void DeleteRange(ICollection entities) 132 | { 133 | _context.Set().RemoveRange(entities); 134 | } 135 | 136 | public virtual async Task DeleteRangeAsync(ICollection entities, CancellationToken cancellationToken = default) 137 | { 138 | _context.Set().RemoveRange(entities); 139 | 140 | return await _context.SaveChangesAsync(cancellationToken); 141 | } 142 | 143 | public virtual void Update(TEntity entity) 144 | { 145 | _context.Set().Update(entity); 146 | } 147 | 148 | public virtual async Task UpdateAsync(TEntity entity, CancellationToken cancellationToken = default) 149 | { 150 | _context.Set().Update(entity); 151 | 152 | return await _context.SaveChangesAsync(cancellationToken); 153 | } 154 | } -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Persistence/Repositories/CustomPostRepository.cs: -------------------------------------------------------------------------------- 1 | using EFCoreRepositoryUnitofWork.Entities; 2 | using EFCoreRepositoryUnitofWork.Interfaces; 3 | using Microsoft.EntityFrameworkCore; 4 | 5 | namespace EFCoreRepositoryUnitofWork.Persistence.Repositories; 6 | 7 | public class CustomPostRepository : BaseRepository, ICustomPostRepository 8 | { 9 | private readonly ApplicationContext _dbContext; 10 | 11 | public CustomPostRepository(ApplicationContext dbContext) : base(dbContext) 12 | { 13 | _dbContext = dbContext; 14 | } 15 | 16 | public override Post Add(Post entity) 17 | { 18 | return base.Add(entity); 19 | } 20 | 21 | public async Task GetPostWithCommentsAsync(int id) 22 | { 23 | IQueryable queryable = GetAll(); 24 | return await queryable.Include(a => a.Comments).FirstOrDefaultAsync(a => a.Id == id); 25 | } 26 | 27 | public IEnumerable GetPostWithMoreComments(int count) 28 | { 29 | return _dbContext.Posts.OrderByDescending(d => d.Comments).Take(count).ToList(); 30 | } 31 | } -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Program.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arbems/EF-Core-Repository-Unit-of-Work/293b6575ee5dfb8aa264b1e458f7058ab58a017c/src/EFCoreRepositoryUnitofWork/Program.cs -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:30951", 8 | "sslPort": 44345 9 | } 10 | }, 11 | "profiles": { 12 | "EFCoreRepositoryUnitofWork": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7139;http://localhost:5139", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "UseInMemoryDatabase": true, 3 | "ConnectionStrings": { 4 | "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=nameDb;Trusted_Connection=True;MultipleActiveResultSets=true;" 5 | }, 6 | "Logging": { 7 | "LogLevel": { 8 | "Default": "Information", 9 | "Microsoft.AspNetCore": "Warning" 10 | } 11 | }, 12 | "AllowedHosts": "*" 13 | } -------------------------------------------------------------------------------- /src/EFCoreRepositoryUnitofWork/wwwroot/swagger-ui/custom.css: -------------------------------------------------------------------------------- 1 | .swagger-ui img { 2 | content: url("https://arbems.com/wp-content/uploads/2022/03/cropped-SocialBook-Cartoonizer-Caricature-1.png"); 3 | height: 70px; 4 | } 5 | .swagger-ui .topbar { 6 | background-color: #FFFFFF; 7 | padding: 10px 0; 8 | color: #000000; 9 | } 10 | .swagger-ui .topbar .download-url-wrapper .select-label { 11 | color: #000000; 12 | } --------------------------------------------------------------------------------