├── .gitattributes ├── .gitignore ├── MyCookingMaster.API ├── Controllers │ ├── IngredientsController.cs │ ├── RecipesController.cs │ └── UsersController.cs ├── MyCookingMaster.API.csproj ├── Program.cs ├── Properties │ └── launchSettings.json ├── Startup.cs ├── appsettings.Development.json └── appsettings.json ├── MyCookingMaster.BL ├── Interfaces │ ├── IRepository.cs │ ├── ISpecification.cs │ └── IUnitOfWork.cs ├── Models │ ├── Common │ │ └── BaseEntity.cs │ ├── Enums │ │ └── RecipeDifficulty.cs │ ├── Ingredient.cs │ ├── Recipe.cs │ └── User.cs ├── MyCookingMaster.BL.csproj └── Specifications │ ├── BaseSpecification.cs │ └── UsersWithRecipesAndIngredientsSpecification.cs ├── MyCookingMaster.DAL ├── ApplicationDbContext.cs ├── Data │ └── DataSeeder.cs ├── Migrations │ ├── 20190210190425_Initial.Designer.cs │ ├── 20190210190425_Initial.cs │ └── ApplicationDbContextModelSnapshot.cs ├── MyCookingMaster.DAL.csproj ├── Repository.cs ├── SpecificationEvaluator.cs └── UnitOfWork.cs ├── MyCookingMaster.sln └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc -------------------------------------------------------------------------------- /MyCookingMaster.API/Controllers/IngredientsController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.EntityFrameworkCore; 3 | using MyCookingMaster.BL.Interfaces; 4 | using MyCookingMaster.BL.Models; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | 8 | namespace MyCookingMaster.API.Controllers 9 | { 10 | [Route("api/[controller]")] 11 | [ApiController] 12 | public class IngredientsController : ControllerBase 13 | { 14 | private readonly IUnitOfWork _unitOfWork; 15 | 16 | public IngredientsController(IUnitOfWork unitOfWork) 17 | { 18 | _unitOfWork = unitOfWork; 19 | } 20 | 21 | // GET: api/Ingredients 22 | [HttpGet] 23 | public ActionResult> GetIngredients() 24 | { 25 | return _unitOfWork.Repository().Find().ToList(); 26 | } 27 | 28 | // GET: api/Ingredients/5 29 | [HttpGet("{id}")] 30 | public ActionResult GetIngredient(int id) 31 | { 32 | var ingredient = _unitOfWork.Repository().FindById(id); 33 | 34 | if (ingredient == null) 35 | { 36 | return NotFound(); 37 | } 38 | 39 | return ingredient; 40 | } 41 | 42 | // PUT: api/Ingredients/5 43 | [HttpPut("{id}")] 44 | public IActionResult PutIngredient(int id, Ingredient ingredient) 45 | { 46 | if (id != ingredient.Id) 47 | { 48 | return BadRequest(); 49 | } 50 | 51 | _unitOfWork.Repository().Update(ingredient); 52 | 53 | try 54 | { 55 | _unitOfWork.Complete(); 56 | } 57 | catch (DbUpdateConcurrencyException) 58 | { 59 | if (!_unitOfWork.Repository().Contains(x => x.Id == id)) 60 | { 61 | return NotFound(); 62 | } 63 | else 64 | { 65 | throw; 66 | } 67 | } 68 | 69 | return NoContent(); 70 | } 71 | 72 | // POST: api/Ingredients 73 | [HttpPost] 74 | public ActionResult PostIngredient(Ingredient ingredient) 75 | { 76 | _unitOfWork.Repository().Add(ingredient); 77 | _unitOfWork.Complete(); 78 | 79 | return CreatedAtAction("GetIngredient", new { id = ingredient.Id }, ingredient); 80 | } 81 | 82 | // DELETE: api/Ingredients/5 83 | [HttpDelete("{id}")] 84 | public ActionResult DeleteIngredient(int id) 85 | { 86 | var ingredient = _unitOfWork.Repository().FindById(id); 87 | if (ingredient == null) 88 | { 89 | return NotFound(); 90 | } 91 | 92 | _unitOfWork.Repository().Remove(ingredient); 93 | _unitOfWork.Complete(); 94 | 95 | return ingredient; 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /MyCookingMaster.API/Controllers/RecipesController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.EntityFrameworkCore; 3 | using MyCookingMaster.BL.Interfaces; 4 | using MyCookingMaster.BL.Models; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | 8 | namespace MyCookingMaster.API.Controllers 9 | { 10 | [Route("api/[controller]")] 11 | [ApiController] 12 | public class RecipeesController : ControllerBase 13 | { 14 | private readonly IUnitOfWork _unitOfWork; 15 | 16 | public RecipeesController(IUnitOfWork unitOfWork) 17 | { 18 | _unitOfWork = unitOfWork; 19 | } 20 | 21 | // GET: api/Recipees 22 | [HttpGet] 23 | public ActionResult> GetRecipees() 24 | { 25 | //return _unitOfWork.Recipes.GetAllIncludingIngredients().ToList(); 26 | return _unitOfWork.Repository().Find().ToList(); 27 | } 28 | 29 | // GET: api/Recipees/5 30 | [HttpGet("{id}")] 31 | public ActionResult GetRecipee(int id) 32 | { 33 | var recipee = _unitOfWork.Repository().FindById(id); 34 | 35 | if (recipee == null) 36 | { 37 | return NotFound(); 38 | } 39 | 40 | return recipee; 41 | } 42 | 43 | //// PUT: api/Recipees/5 44 | [HttpPut("{id}")] 45 | public IActionResult PutUser(int id, Recipe recipee) 46 | { 47 | if (id != recipee.Id) 48 | { 49 | return BadRequest(); 50 | } 51 | 52 | _unitOfWork.Repository().Update(recipee); 53 | 54 | try 55 | { 56 | _unitOfWork.Complete(); 57 | } 58 | catch (DbUpdateConcurrencyException) 59 | { 60 | if (!_unitOfWork.Repository().Contains(x => x.Id == id)) 61 | { 62 | return NotFound(); 63 | } 64 | else 65 | { 66 | throw; 67 | } 68 | } 69 | 70 | return NoContent(); 71 | } 72 | 73 | // POST: api/Recipees 74 | [HttpPost] 75 | public ActionResult PostRecipee(Recipe recipee) 76 | { 77 | _unitOfWork.Repository().Add(recipee); 78 | _unitOfWork.Complete(); 79 | 80 | return CreatedAtAction("GetRecipee", new { id = recipee.Id }, recipee); 81 | } 82 | 83 | // DELETE: api/Recipees/5 84 | [HttpDelete("{id}")] 85 | public ActionResult DeleteRecipee(int id) 86 | { 87 | var recipee = _unitOfWork.Repository().FindById(id); 88 | if (recipee == null) 89 | { 90 | return NotFound(); 91 | } 92 | 93 | _unitOfWork.Repository().Remove(recipee); 94 | _unitOfWork.Complete(); 95 | 96 | return recipee; 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /MyCookingMaster.API/Controllers/UsersController.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using Microsoft.AspNetCore.Mvc; 4 | using Microsoft.EntityFrameworkCore; 5 | using MyCookingMaster.BL.Interfaces; 6 | using MyCookingMaster.BL.Models; 7 | using MyCookingMaster.BL.Specifications; 8 | 9 | namespace MyCookingMaster.API.Controllers 10 | { 11 | [Route("api/[controller]")] 12 | [ApiController] 13 | public class UsersController : ControllerBase 14 | { 15 | private readonly IUnitOfWork _unitOfWork; 16 | 17 | public UsersController(IUnitOfWork unitOfWork) 18 | { 19 | _unitOfWork = unitOfWork; 20 | } 21 | 22 | // GET: api/Users 23 | [HttpGet] 24 | public ActionResult> GetUsers() 25 | { 26 | return _unitOfWork.Repository().Find(new UsersWithRecipesAndIngredientsSpecification()).ToList(); 27 | } 28 | 29 | // GET: api/Users/5 30 | [HttpGet("{id}")] 31 | public ActionResult GetUser(int id) 32 | { 33 | var user = _unitOfWork.Repository().Find(new UsersWithRecipesAndIngredientsSpecification(id)).SingleOrDefault(); 34 | 35 | if (user == null) 36 | { 37 | return NotFound(); 38 | } 39 | 40 | return user; 41 | } 42 | 43 | //// PUT: api/Users/5 44 | [HttpPut("{id}")] 45 | public IActionResult PutUser(int id, User user) 46 | { 47 | if (id != user.Id) 48 | { 49 | return BadRequest(); 50 | } 51 | 52 | _unitOfWork.Repository().Update(user); 53 | 54 | try 55 | { 56 | _unitOfWork.Complete(); 57 | } 58 | catch (DbUpdateConcurrencyException) 59 | { 60 | if(!_unitOfWork.Repository().Contains(x => x.Id == id)) 61 | { 62 | return NotFound(); 63 | } 64 | else 65 | { 66 | throw; 67 | } 68 | } 69 | 70 | return NoContent(); 71 | } 72 | 73 | // POST: api/Users 74 | [HttpPost] 75 | public ActionResult PostUser(User user) 76 | { 77 | _unitOfWork.Repository().Add(user); 78 | _unitOfWork.Complete(); 79 | 80 | return CreatedAtAction("GetUser", new { id = user.Id }, user); 81 | } 82 | 83 | // DELETE: api/Users/5 84 | [HttpDelete("{id}")] 85 | public ActionResult DeleteUser(int id) 86 | { 87 | var user = _unitOfWork.Repository().FindById(id); 88 | if (user == null) 89 | { 90 | return NotFound(); 91 | } 92 | 93 | _unitOfWork.Repository().Remove(user); 94 | _unitOfWork.Complete(); 95 | 96 | return user; 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /MyCookingMaster.API/MyCookingMaster.API.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.2 5 | InProcess 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /MyCookingMaster.API/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.AspNetCore; 3 | using Microsoft.AspNetCore.Hosting; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using MyCookingMaster.DAL; 6 | using MyCookingMaster.DAL.Data; 7 | 8 | namespace MyCookingMaster.API 9 | { 10 | public class Program 11 | { 12 | public static void Main(string[] args) 13 | { 14 | var host = CreateWebHostBuilder(args).Build(); 15 | 16 | using (var scope = host.Services.CreateScope()) 17 | { 18 | var services = scope.ServiceProvider; 19 | try 20 | { 21 | var context = services.GetRequiredService(); 22 | DataSeeder.Initialize(context); 23 | } 24 | catch (Exception) 25 | { 26 | Console.WriteLine("An error occurred while seeding the database."); 27 | } 28 | } 29 | host.Run(); 30 | } 31 | 32 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 33 | WebHost.CreateDefaultBuilder(args) 34 | .UseStartup(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /MyCookingMaster.API/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:64572", 8 | "sslPort": 44309 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "api/users", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "MyCookingMaster.API": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "api/values", 24 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /MyCookingMaster.API/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.AspNetCore.Mvc; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using MyCookingMaster.BL.Interfaces; 8 | using MyCookingMaster.DAL; 9 | 10 | namespace MyCookingMaster.API 11 | { 12 | public class Startup 13 | { 14 | public Startup(IConfiguration configuration) 15 | { 16 | Configuration = configuration; 17 | } 18 | 19 | public IConfiguration Configuration { get; } 20 | 21 | // This method gets called by the runtime. Use this method to add services to the container. 22 | public void ConfigureServices(IServiceCollection services) 23 | { 24 | services.AddDbContext(options => 25 | options.UseSqlServer(Configuration.GetConnectionString("DatabaseConnection"))); 26 | 27 | services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2) 28 | .AddJsonOptions(options => 29 | { 30 | options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 31 | }); 32 | 33 | services.AddTransient(); 34 | } 35 | 36 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 37 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) 38 | { 39 | if (env.IsDevelopment()) 40 | { 41 | app.UseDeveloperExceptionPage(); 42 | } 43 | else 44 | { 45 | // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. 46 | app.UseHsts(); 47 | } 48 | 49 | app.UseHttpsRedirection(); 50 | app.UseMvc(); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /MyCookingMaster.API/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /MyCookingMaster.API/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionStrings": { 3 | "DatabaseConnection": "Server=(localdb)\\mssqllocaldb;Database=MyCookingMaster;Trusted_Connection=True" 4 | }, 5 | "Logging": { 6 | "LogLevel": { 7 | "Default": "Warning" 8 | } 9 | }, 10 | "AllowedHosts": "*" 11 | } 12 | -------------------------------------------------------------------------------- /MyCookingMaster.BL/Interfaces/IRepository.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq.Expressions; 4 | 5 | namespace MyCookingMaster.BL.Interfaces 6 | { 7 | public interface IRepository where TEntity : class 8 | { 9 | TEntity FindById(int id); 10 | 11 | IEnumerable Find(ISpecification specification = null); 12 | 13 | void Add(TEntity entity); 14 | void AddRange(IEnumerable entities); 15 | 16 | void Remove(TEntity entity); 17 | void RemoveRange(IEnumerable entities); 18 | 19 | void Update(TEntity entity); 20 | 21 | bool Contains(ISpecification specification = null); 22 | bool Contains(Expression> predicate); 23 | 24 | int Count(ISpecification specification = null); 25 | int Count(Expression> predicate); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /MyCookingMaster.BL/Interfaces/ISpecification.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq.Expressions; 4 | 5 | namespace MyCookingMaster.BL.Interfaces 6 | { 7 | public interface ISpecification 8 | { 9 | Expression> Criteria { get; } 10 | List>> Includes { get; } 11 | List IncludeStrings { get; } 12 | Expression> OrderBy { get; } 13 | Expression> OrderByDescending { get; } 14 | Expression> GroupBy { get; } 15 | 16 | int Take { get; } 17 | int Skip { get; } 18 | bool IsPagingEnabled { get; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /MyCookingMaster.BL/Interfaces/IUnitOfWork.cs: -------------------------------------------------------------------------------- 1 | using MyCookingMaster.BL.Models.Common; 2 | using System; 3 | 4 | namespace MyCookingMaster.BL.Interfaces 5 | { 6 | public interface IUnitOfWork : IDisposable 7 | { 8 | IRepository Repository() where TEntity : BaseEntity; 9 | int Complete(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /MyCookingMaster.BL/Models/Common/BaseEntity.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace MyCookingMaster.BL.Models.Common 4 | { 5 | public abstract class BaseEntity 6 | { 7 | [Key] 8 | public int Id { get; set; } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /MyCookingMaster.BL/Models/Enums/RecipeDifficulty.cs: -------------------------------------------------------------------------------- 1 | namespace MyCookingMaster.BL.Models.Enums 2 | { 3 | public enum RecipeDifficulty 4 | { 5 | EASY, 6 | MEDIUM, 7 | HARD 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /MyCookingMaster.BL/Models/Ingredient.cs: -------------------------------------------------------------------------------- 1 | using MyCookingMaster.BL.Models.Common; 2 | using System.ComponentModel.DataAnnotations.Schema; 3 | 4 | namespace MyCookingMaster.BL.Models 5 | { 6 | public class Ingredient : BaseEntity 7 | { 8 | public string Name { get; set; } 9 | public int Amount { get; set; } 10 | 11 | [ForeignKey("Recipe")] 12 | public int RecipeId { get; set; } 13 | public Recipe Recipe { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /MyCookingMaster.BL/Models/Recipe.cs: -------------------------------------------------------------------------------- 1 | using MyCookingMaster.BL.Models.Common; 2 | using MyCookingMaster.BL.Models.Enums; 3 | using System.Collections.Generic; 4 | using System.ComponentModel.DataAnnotations.Schema; 5 | 6 | namespace MyCookingMaster.BL.Models 7 | { 8 | public class Recipe : BaseEntity 9 | { 10 | public string Name { get; set; } 11 | public string Description { get; set; } 12 | public string ImagePath { get; set; } 13 | public RecipeDifficulty Difficulty { get; set; } 14 | public int Time { get; set; } 15 | 16 | public IEnumerable Ingredients { get; set; } 17 | 18 | [ForeignKey("User")] 19 | public int UserId { get; set; } 20 | public User User { get; set; } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /MyCookingMaster.BL/Models/User.cs: -------------------------------------------------------------------------------- 1 | using MyCookingMaster.BL.Models.Common; 2 | using System.Collections.Generic; 3 | 4 | namespace MyCookingMaster.BL.Models 5 | { 6 | public class User : BaseEntity 7 | { 8 | public string Name { get; set; } 9 | public string Email { get; set; } 10 | 11 | public IEnumerable Recipes { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /MyCookingMaster.BL/MyCookingMaster.BL.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.2 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /MyCookingMaster.BL/Specifications/BaseSpecification.cs: -------------------------------------------------------------------------------- 1 | using MyCookingMaster.BL.Interfaces; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq.Expressions; 5 | 6 | namespace MyCookingMaster.BL 7 | { 8 | public abstract class BaseSpecification : ISpecification 9 | { 10 | protected BaseSpecification(Expression> criteria) 11 | { 12 | Criteria = criteria; 13 | } 14 | protected BaseSpecification() 15 | { 16 | 17 | } 18 | public Expression> Criteria { get; } 19 | public List>> Includes { get; } = new List>>(); 20 | public List IncludeStrings { get; } = new List(); 21 | public Expression> OrderBy { get; private set; } 22 | public Expression> OrderByDescending { get; private set; } 23 | public Expression> GroupBy { get; private set; } 24 | 25 | public int Take { get; private set; } 26 | public int Skip { get; private set; } 27 | public bool IsPagingEnabled { get; private set; } = false; 28 | 29 | protected virtual void AddInclude(Expression> includeExpression) 30 | { 31 | Includes.Add(includeExpression); 32 | } 33 | 34 | protected virtual void AddInclude(string includeString) 35 | { 36 | IncludeStrings.Add(includeString); 37 | } 38 | 39 | protected virtual void ApplyPaging(int skip, int take) 40 | { 41 | Skip = skip; 42 | Take = take; 43 | IsPagingEnabled = true; 44 | } 45 | 46 | protected virtual void ApplyOrderBy(Expression> orderByExpression) 47 | { 48 | OrderBy = orderByExpression; 49 | } 50 | 51 | protected virtual void ApplyOrderByDescending(Expression> orderByDescendingExpression) 52 | { 53 | OrderByDescending = orderByDescendingExpression; 54 | } 55 | 56 | protected virtual void ApplyGroupBy(Expression> groupByExpression) 57 | { 58 | GroupBy = groupByExpression; 59 | } 60 | 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /MyCookingMaster.BL/Specifications/UsersWithRecipesAndIngredientsSpecification.cs: -------------------------------------------------------------------------------- 1 | using MyCookingMaster.BL.Models; 2 | 3 | namespace MyCookingMaster.BL.Specifications 4 | { 5 | public class UsersWithRecipesAndIngredientsSpecification : BaseSpecification 6 | { 7 | public UsersWithRecipesAndIngredientsSpecification() : base() 8 | { 9 | AddInclude(x => x.Recipes); 10 | AddInclude($"{nameof(User.Recipes)}.{nameof(Recipe.Ingredients)}"); 11 | } 12 | 13 | public UsersWithRecipesAndIngredientsSpecification(int id) : base(x => x.Id == id) 14 | { 15 | AddInclude(x => x.Recipes); 16 | AddInclude($"{nameof(User.Recipes)}.{nameof(Recipe.Ingredients)}"); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /MyCookingMaster.DAL/ApplicationDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Design; 3 | using Microsoft.Extensions.Configuration; 4 | using MyCookingMaster.BL.Models; 5 | using System.IO; 6 | 7 | namespace MyCookingMaster.DAL 8 | { 9 | public class ApplicationDbContext : DbContext 10 | { 11 | public ApplicationDbContext(DbContextOptions options) : base(options) { } 12 | 13 | public virtual DbSet Users { get; set; } 14 | public virtual DbSet Recipes { get; set; } 15 | public virtual DbSet Ingredients { get; set; } 16 | } 17 | 18 | public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory 19 | { 20 | public ApplicationDbContext CreateDbContext(string[] args) 21 | { 22 | IConfigurationRoot configuration = new ConfigurationBuilder() 23 | .SetBasePath(Directory.GetCurrentDirectory()) 24 | .AddJsonFile(@Directory.GetCurrentDirectory() + "/../MyCookingMaster.API/appsettings.json") 25 | .Build(); 26 | var builder = new DbContextOptionsBuilder(); 27 | var connectionString = configuration.GetConnectionString("DatabaseConnection"); 28 | builder.UseSqlServer(connectionString); 29 | return new ApplicationDbContext(builder.Options); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /MyCookingMaster.DAL/Data/DataSeeder.cs: -------------------------------------------------------------------------------- 1 | using MyCookingMaster.BL.Models; 2 | using MyCookingMaster.BL.Models.Enums; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | namespace MyCookingMaster.DAL.Data 7 | { 8 | public class DataSeeder 9 | { 10 | public static void Initialize(ApplicationDbContext context) 11 | { 12 | if (!context.Users.Any()) 13 | { 14 | var users = new List() 15 | { 16 | new User { /*Id = 1,*/ Name = "John", Email = "john@john.com" }, 17 | new User { /*Id = 2,*/ Name = "Michael", Email = "michael@michael.com" } 18 | }; 19 | context.Users.AddRange(users); 20 | context.SaveChanges(); 21 | } 22 | 23 | if (!context.Recipes.Any()) 24 | { 25 | var recipes = new List() 26 | { 27 | new Recipe { /* Id = 1 */ Name = "Pizza", Description = "A random description from a pizza", Difficulty = RecipeDifficulty.MEDIUM, ImagePath = "https://upload.wikimedia.org/wikipedia/commons/a/a4/Pizza.jpg", Time = 30, UserId = 1 } 28 | }; 29 | context.Recipes.AddRange(recipes); 30 | context.SaveChanges(); 31 | } 32 | 33 | if (!context.Ingredients.Any()) 34 | { 35 | var ingredients = new List() 36 | { 37 | new Ingredient { /* Id = 1 */ Name = "Cheese", Amount = 1, RecipeId = 1 }, 38 | new Ingredient { /* Id = 2 */ Name = "Tomato", Amount = 2, RecipeId = 1 } 39 | }; 40 | context.Ingredients.AddRange(ingredients); 41 | context.SaveChanges(); 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /MyCookingMaster.DAL/Migrations/20190210190425_Initial.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | using MyCookingMaster.DAL; 8 | 9 | namespace MyCookingMaster.DAL.Migrations 10 | { 11 | [DbContext(typeof(ApplicationDbContext))] 12 | [Migration("20190210190425_Initial")] 13 | partial class Initial 14 | { 15 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 16 | { 17 | #pragma warning disable 612, 618 18 | modelBuilder 19 | .HasAnnotation("ProductVersion", "2.2.1-servicing-10028") 20 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 21 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 22 | 23 | modelBuilder.Entity("MyCookingMaster.BL.Models.Ingredient", b => 24 | { 25 | b.Property("Id") 26 | .ValueGeneratedOnAdd() 27 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 28 | 29 | b.Property("Amount"); 30 | 31 | b.Property("Name"); 32 | 33 | b.Property("RecipeId"); 34 | 35 | b.HasKey("Id"); 36 | 37 | b.HasIndex("RecipeId"); 38 | 39 | b.ToTable("Ingredients"); 40 | }); 41 | 42 | modelBuilder.Entity("MyCookingMaster.BL.Models.Recipe", b => 43 | { 44 | b.Property("Id") 45 | .ValueGeneratedOnAdd() 46 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 47 | 48 | b.Property("Description"); 49 | 50 | b.Property("Difficulty"); 51 | 52 | b.Property("ImagePath"); 53 | 54 | b.Property("Name"); 55 | 56 | b.Property("Time"); 57 | 58 | b.Property("UserId"); 59 | 60 | b.HasKey("Id"); 61 | 62 | b.HasIndex("UserId"); 63 | 64 | b.ToTable("Recipes"); 65 | }); 66 | 67 | modelBuilder.Entity("MyCookingMaster.BL.Models.User", b => 68 | { 69 | b.Property("Id") 70 | .ValueGeneratedOnAdd() 71 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 72 | 73 | b.Property("Email"); 74 | 75 | b.Property("Name"); 76 | 77 | b.HasKey("Id"); 78 | 79 | b.ToTable("Users"); 80 | }); 81 | 82 | modelBuilder.Entity("MyCookingMaster.BL.Models.Ingredient", b => 83 | { 84 | b.HasOne("MyCookingMaster.BL.Models.Recipe", "Recipe") 85 | .WithMany("Ingredients") 86 | .HasForeignKey("RecipeId") 87 | .OnDelete(DeleteBehavior.Cascade); 88 | }); 89 | 90 | modelBuilder.Entity("MyCookingMaster.BL.Models.Recipe", b => 91 | { 92 | b.HasOne("MyCookingMaster.BL.Models.User", "User") 93 | .WithMany("Recipes") 94 | .HasForeignKey("UserId") 95 | .OnDelete(DeleteBehavior.Cascade); 96 | }); 97 | #pragma warning restore 612, 618 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /MyCookingMaster.DAL/Migrations/20190210190425_Initial.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Metadata; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | namespace MyCookingMaster.DAL.Migrations 5 | { 6 | public partial class Initial : Migration 7 | { 8 | protected override void Up(MigrationBuilder migrationBuilder) 9 | { 10 | migrationBuilder.CreateTable( 11 | name: "Users", 12 | columns: table => new 13 | { 14 | Id = table.Column(nullable: false) 15 | .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), 16 | Name = table.Column(nullable: true), 17 | Email = table.Column(nullable: true) 18 | }, 19 | constraints: table => 20 | { 21 | table.PrimaryKey("PK_Users", x => x.Id); 22 | }); 23 | 24 | migrationBuilder.CreateTable( 25 | name: "Recipes", 26 | columns: table => new 27 | { 28 | Id = table.Column(nullable: false) 29 | .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), 30 | Name = table.Column(nullable: true), 31 | Description = table.Column(nullable: true), 32 | ImagePath = table.Column(nullable: true), 33 | Difficulty = table.Column(nullable: false), 34 | Time = table.Column(nullable: false), 35 | UserId = table.Column(nullable: false) 36 | }, 37 | constraints: table => 38 | { 39 | table.PrimaryKey("PK_Recipes", x => x.Id); 40 | table.ForeignKey( 41 | name: "FK_Recipes_Users_UserId", 42 | column: x => x.UserId, 43 | principalTable: "Users", 44 | principalColumn: "Id", 45 | onDelete: ReferentialAction.Cascade); 46 | }); 47 | 48 | migrationBuilder.CreateTable( 49 | name: "Ingredients", 50 | columns: table => new 51 | { 52 | Id = table.Column(nullable: false) 53 | .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), 54 | Name = table.Column(nullable: true), 55 | Amount = table.Column(nullable: false), 56 | RecipeId = table.Column(nullable: false) 57 | }, 58 | constraints: table => 59 | { 60 | table.PrimaryKey("PK_Ingredients", x => x.Id); 61 | table.ForeignKey( 62 | name: "FK_Ingredients_Recipes_RecipeId", 63 | column: x => x.RecipeId, 64 | principalTable: "Recipes", 65 | principalColumn: "Id", 66 | onDelete: ReferentialAction.Cascade); 67 | }); 68 | 69 | migrationBuilder.CreateIndex( 70 | name: "IX_Ingredients_RecipeId", 71 | table: "Ingredients", 72 | column: "RecipeId"); 73 | 74 | migrationBuilder.CreateIndex( 75 | name: "IX_Recipes_UserId", 76 | table: "Recipes", 77 | column: "UserId"); 78 | } 79 | 80 | protected override void Down(MigrationBuilder migrationBuilder) 81 | { 82 | migrationBuilder.DropTable( 83 | name: "Ingredients"); 84 | 85 | migrationBuilder.DropTable( 86 | name: "Recipes"); 87 | 88 | migrationBuilder.DropTable( 89 | name: "Users"); 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /MyCookingMaster.DAL/Migrations/ApplicationDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 6 | using MyCookingMaster.DAL; 7 | 8 | namespace MyCookingMaster.DAL.Migrations 9 | { 10 | [DbContext(typeof(ApplicationDbContext))] 11 | partial class ApplicationDbContextModelSnapshot : ModelSnapshot 12 | { 13 | protected override void BuildModel(ModelBuilder modelBuilder) 14 | { 15 | #pragma warning disable 612, 618 16 | modelBuilder 17 | .HasAnnotation("ProductVersion", "2.2.1-servicing-10028") 18 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 19 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 20 | 21 | modelBuilder.Entity("MyCookingMaster.BL.Models.Ingredient", b => 22 | { 23 | b.Property("Id") 24 | .ValueGeneratedOnAdd() 25 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 26 | 27 | b.Property("Amount"); 28 | 29 | b.Property("Name"); 30 | 31 | b.Property("RecipeId"); 32 | 33 | b.HasKey("Id"); 34 | 35 | b.HasIndex("RecipeId"); 36 | 37 | b.ToTable("Ingredients"); 38 | }); 39 | 40 | modelBuilder.Entity("MyCookingMaster.BL.Models.Recipe", b => 41 | { 42 | b.Property("Id") 43 | .ValueGeneratedOnAdd() 44 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 45 | 46 | b.Property("Description"); 47 | 48 | b.Property("Difficulty"); 49 | 50 | b.Property("ImagePath"); 51 | 52 | b.Property("Name"); 53 | 54 | b.Property("Time"); 55 | 56 | b.Property("UserId"); 57 | 58 | b.HasKey("Id"); 59 | 60 | b.HasIndex("UserId"); 61 | 62 | b.ToTable("Recipes"); 63 | }); 64 | 65 | modelBuilder.Entity("MyCookingMaster.BL.Models.User", b => 66 | { 67 | b.Property("Id") 68 | .ValueGeneratedOnAdd() 69 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 70 | 71 | b.Property("Email"); 72 | 73 | b.Property("Name"); 74 | 75 | b.HasKey("Id"); 76 | 77 | b.ToTable("Users"); 78 | }); 79 | 80 | modelBuilder.Entity("MyCookingMaster.BL.Models.Ingredient", b => 81 | { 82 | b.HasOne("MyCookingMaster.BL.Models.Recipe", "Recipe") 83 | .WithMany("Ingredients") 84 | .HasForeignKey("RecipeId") 85 | .OnDelete(DeleteBehavior.Cascade); 86 | }); 87 | 88 | modelBuilder.Entity("MyCookingMaster.BL.Models.Recipe", b => 89 | { 90 | b.HasOne("MyCookingMaster.BL.Models.User", "User") 91 | .WithMany("Recipes") 92 | .HasForeignKey("UserId") 93 | .OnDelete(DeleteBehavior.Cascade); 94 | }); 95 | #pragma warning restore 612, 618 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /MyCookingMaster.DAL/MyCookingMaster.DAL.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /MyCookingMaster.DAL/Repository.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using MyCookingMaster.BL.Interfaces; 3 | using MyCookingMaster.BL.Models.Common; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Linq.Expressions; 8 | 9 | namespace MyCookingMaster.DAL.Repositories 10 | { 11 | public class Repository : IRepository where TEntity : BaseEntity 12 | { 13 | protected readonly DbContext _context; 14 | 15 | public Repository(DbContext context) 16 | { 17 | _context = context; 18 | } 19 | 20 | public void Add(TEntity entity) 21 | { 22 | _context.Set().Add(entity); 23 | } 24 | 25 | public void AddRange(IEnumerable entities) 26 | { 27 | _context.Set().AddRange(entities); 28 | } 29 | 30 | public bool Contains(ISpecification specification = null) 31 | { 32 | return Count(specification) > 0 ? true : false; 33 | } 34 | 35 | public bool Contains(Expression> predicate) 36 | { 37 | return Count(predicate) > 0 ? true : false; 38 | } 39 | 40 | public int Count(ISpecification specification = null) 41 | { 42 | return ApplySpecification(specification).Count(); 43 | } 44 | 45 | public int Count(Expression> predicate) 46 | { 47 | return _context.Set().Where(predicate).Count(); 48 | } 49 | 50 | public IEnumerable Find(ISpecification specification = null) 51 | { 52 | return ApplySpecification(specification); 53 | } 54 | 55 | public TEntity FindById(int id) 56 | { 57 | return _context.Set().Find(id); 58 | } 59 | 60 | public void Remove(TEntity entity) 61 | { 62 | _context.Set().Remove(entity); 63 | } 64 | 65 | public void RemoveRange(IEnumerable entities) 66 | { 67 | _context.Set().RemoveRange(entities); 68 | } 69 | 70 | public void Update(TEntity entity) 71 | { 72 | _context.Set().Attach(entity); 73 | _context.Entry(entity).State = EntityState.Modified; 74 | } 75 | 76 | private IQueryable ApplySpecification(ISpecification spec) 77 | { 78 | return SpecificationEvaluator.GetQuery(_context.Set().AsQueryable(), spec); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /MyCookingMaster.DAL/SpecificationEvaluator.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using MyCookingMaster.BL.Interfaces; 3 | using MyCookingMaster.BL.Models.Common; 4 | using System.Linq; 5 | 6 | namespace MyCookingMaster.DAL 7 | { 8 | public class SpecificationEvaluator where TEntity : BaseEntity 9 | { 10 | public static IQueryable GetQuery(IQueryable inputQuery, ISpecification specification) 11 | { 12 | var query = inputQuery; 13 | 14 | // modify the IQueryable using the specification's criteria expression 15 | if (specification.Criteria != null) 16 | { 17 | query = query.Where(specification.Criteria); 18 | } 19 | 20 | // Includes all expression-based includes 21 | query = specification.Includes.Aggregate(query, 22 | (current, include) => current.Include(include)); 23 | 24 | // Include any string-based include statements 25 | query = specification.IncludeStrings.Aggregate(query, 26 | (current, include) => current.Include(include)); 27 | 28 | // Apply ordering if expressions are set 29 | if (specification.OrderBy != null) 30 | { 31 | query = query.OrderBy(specification.OrderBy); 32 | } 33 | else if (specification.OrderByDescending != null) 34 | { 35 | query = query.OrderByDescending(specification.OrderByDescending); 36 | } 37 | 38 | if (specification.GroupBy != null) 39 | { 40 | query = query.GroupBy(specification.GroupBy).SelectMany(x => x); 41 | } 42 | 43 | // Apply paging if enabled 44 | if (specification.IsPagingEnabled) 45 | { 46 | query = query.Skip(specification.Skip) 47 | .Take(specification.Take); 48 | } 49 | return query; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /MyCookingMaster.DAL/UnitOfWork.cs: -------------------------------------------------------------------------------- 1 | using MyCookingMaster.BL.Interfaces; 2 | using MyCookingMaster.BL.Models.Common; 3 | using MyCookingMaster.DAL.Repositories; 4 | using System; 5 | using System.Collections; 6 | 7 | namespace MyCookingMaster.DAL 8 | { 9 | public class UnitOfWork : IUnitOfWork 10 | { 11 | private readonly ApplicationDbContext _context; 12 | private Hashtable _repositories; 13 | 14 | public UnitOfWork(ApplicationDbContext context) 15 | { 16 | _context = context; 17 | } 18 | 19 | public int Complete() 20 | { 21 | return _context.SaveChanges(); 22 | } 23 | 24 | public IRepository Repository() where TEntity : BaseEntity 25 | { 26 | if (_repositories == null) 27 | _repositories = new Hashtable(); 28 | 29 | var type = typeof(TEntity).Name; 30 | 31 | if (!_repositories.ContainsKey(type)) 32 | { 33 | var repositoryType = typeof(Repository<>); 34 | 35 | var repositoryInstance = 36 | Activator.CreateInstance(repositoryType 37 | .MakeGenericType(typeof(TEntity)), _context); 38 | 39 | _repositories.Add(type, repositoryInstance); 40 | } 41 | 42 | return (IRepository)_repositories[type]; 43 | } 44 | 45 | public void Dispose() 46 | { 47 | _context.Dispose(); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /MyCookingMaster.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.28307.168 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyCookingMaster.API", "MyCookingMaster.API\MyCookingMaster.API.csproj", "{E7A75D92-8A9A-4AA2-993F-BA4E2B0BC6C6}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyCookingMaster.BL", "MyCookingMaster.BL\MyCookingMaster.BL.csproj", "{C1AD4702-1D3F-415F-B8B4-3D38A1F77244}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyCookingMaster.DAL", "MyCookingMaster.DAL\MyCookingMaster.DAL.csproj", "{A55C66F9-6F88-4AEE-A65C-EE38C67C2047}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {E7A75D92-8A9A-4AA2-993F-BA4E2B0BC6C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {E7A75D92-8A9A-4AA2-993F-BA4E2B0BC6C6}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {E7A75D92-8A9A-4AA2-993F-BA4E2B0BC6C6}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {E7A75D92-8A9A-4AA2-993F-BA4E2B0BC6C6}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {C1AD4702-1D3F-415F-B8B4-3D38A1F77244}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {C1AD4702-1D3F-415F-B8B4-3D38A1F77244}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {C1AD4702-1D3F-415F-B8B4-3D38A1F77244}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {C1AD4702-1D3F-415F-B8B4-3D38A1F77244}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {A55C66F9-6F88-4AEE-A65C-EE38C67C2047}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {A55C66F9-6F88-4AEE-A65C-EE38C67C2047}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {A55C66F9-6F88-4AEE-A65C-EE38C67C2047}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {A55C66F9-6F88-4AEE-A65C-EE38C67C2047}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {CEBF1030-B433-4EA8-9E92-01A5121E6E18} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SpecificationAndRepository 2 | 3 | Sample code for my blog post [.NET Core - Using the Specification pattern alongside a generic Repository](https://www.rodrigosantosdev.com/Blog/net-core--using-the-specification-pattern-alongside-a-generic-repository) 4 | --------------------------------------------------------------------------------