Skip to content

Commit

Permalink
Merge pull request #11 from mahmmoudkinawy/master
Browse files Browse the repository at this point in the history
Refactoring and Upgrading to .net 5.0
  • Loading branch information
evgomes authored Nov 26, 2021
2 parents e480aea + 3ed9422 commit 3d05025
Show file tree
Hide file tree
Showing 11 changed files with 127 additions and 75 deletions.
12 changes: 12 additions & 0 deletions src/Supermarket.API/Controllers/BaseApiController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc;

namespace Supermarket.API.Controllers
{
[Route("/api/[controller]")]
[Produces("application/json")]
[ApiController]
public class BaseApiController : ControllerBase
{

}
}
5 changes: 1 addition & 4 deletions src/Supermarket.API/Controllers/CategoriesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@

namespace Supermarket.API.Controllers
{
[Route("/api/categories")]
[Produces("application/json")]
[ApiController]
public class CategoriesController : Controller
public class CategoriesController : BaseApiController
{
private readonly ICategoryService _categoryService;
private readonly IMapper _mapper;
Expand Down
6 changes: 1 addition & 5 deletions src/Supermarket.API/Controllers/ProductsController.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
Expand All @@ -9,10 +8,7 @@

namespace Supermarket.API.Controllers
{
[Route("/api/products")]
[Produces("application/json")]
[ApiController]
public class ProductsController : Controller
public class ProductsController : BaseApiController
{
private readonly IProductService _productService;
private readonly IMapper _mapper;
Expand Down
45 changes: 3 additions & 42 deletions src/Supermarket.API/Persistence/Contexts/AppDbContext.cs
Original file line number Diff line number Diff line change
@@ -1,58 +1,19 @@
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.InMemory.ValueGeneration.Internal;
using Supermarket.API.Domain.Models;

namespace Supermarket.API.Persistence.Contexts
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }

public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);

builder.Entity<Category>().ToTable("Categories");
builder.Entity<Category>().HasKey(p => p.Id);
builder.Entity<Category>().Property(p => p.Id).IsRequired().ValueGeneratedOnAdd();//.HasValueGenerator<InMemoryIntegerValueGenerator<int>>();
builder.Entity<Category>().Property(p => p.Name).IsRequired().HasMaxLength(30);
builder.Entity<Category>().HasMany(p => p.Products).WithOne(p => p.Category).HasForeignKey(p => p.CategoryId);

builder.Entity<Category>().HasData
(
new Category { Id = 100, Name = "Fruits and Vegetables" }, // Id set manually due to in-memory provider
new Category { Id = 101, Name = "Dairy" }
);

builder.Entity<Product>().ToTable("Products");
builder.Entity<Product>().HasKey(p => p.Id);
builder.Entity<Product>().Property(p => p.Id).IsRequired().ValueGeneratedOnAdd();
builder.Entity<Product>().Property(p => p.Name).IsRequired().HasMaxLength(50);
builder.Entity<Product>().Property(p => p.QuantityInPackage).IsRequired();
builder.Entity<Product>().Property(p => p.UnitOfMeasurement).IsRequired();

builder.Entity<Product>().HasData
(
new Product
{
Id = 100,
Name = "Apple",
QuantityInPackage = 1,
UnitOfMeasurement = EUnitOfMeasurement.Unity,
CategoryId = 100
},
new Product
{
Id = 101,
Name = "Milk",
QuantityInPackage = 2,
UnitOfMeasurement = EUnitOfMeasurement.Liter,
CategoryId = 101,
}
);
builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Supermarket.API.Domain.Models;

namespace Supermarket.API.Persistence.Contexts.Configurations
{
public class CategoryConfiguration : IEntityTypeConfiguration<Category>
{
public void Configure(EntityTypeBuilder<Category> builder)
{
builder.ToTable("Categories");
builder.HasKey(p => p.Id);
builder.Property(p => p.Id).IsRequired().ValueGeneratedOnAdd();//.HasValueGenerator<InMemoryIntegerValueGenerator<int>>();
builder.Property(p => p.Name).IsRequired().HasMaxLength(30);
builder.HasMany(p => p.Products).WithOne(p => p.Category).HasForeignKey(p => p.CategoryId);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Supermarket.API.Domain.Models;

namespace Supermarket.API.Persistence.Contexts.Configurations
{
public class ProductConfiguration : IEntityTypeConfiguration<Product>
{
public void Configure(EntityTypeBuilder<Product> builder)
{
builder.ToTable("Products");
builder.HasKey(p => p.Id);
builder.Property(p => p.Id).IsRequired().ValueGeneratedOnAdd();
builder.Property(p => p.Name).IsRequired().HasMaxLength(50);
builder.Property(p => p.QuantityInPackage).IsRequired();
builder.Property(p => p.UnitOfMeasurement).IsRequired();
}
}
}
43 changes: 43 additions & 0 deletions src/Supermarket.API/Persistence/Contexts/SeedData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Supermarket.API.Domain.Models;

namespace Supermarket.API.Persistence.Contexts
{
public static class SeedData
{
public static async Task Seed(AppDbContext context)
{
var products = new List<Product>
{
new Product
{
Id = 100,
Name = "Apple",
QuantityInPackage = 1,
UnitOfMeasurement = EUnitOfMeasurement.Unity,
CategoryId = 100
},
new Product
{
Id = 101,
Name = "Milk",
QuantityInPackage = 2,
UnitOfMeasurement = EUnitOfMeasurement.Liter,
CategoryId = 101,
}
};

var categories = new List<Category>
{
new Category { Id = 100, Name = "Fruits and Vegetables" }, // Id set manually due to in-memory provider
new Category { Id = 101, Name = "Dairy" }
};

context.Products.AddRange(products);
context.Categories.AddRange(categories);

await context.SaveChangesAsync();
}
}
}
23 changes: 16 additions & 7 deletions src/Supermarket.API/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
using Microsoft.AspNetCore.Hosting;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Supermarket.API.Persistence.Contexts;

namespace Supermarket.API
Expand All @@ -9,17 +12,23 @@ namespace Supermarket.API
#pragma warning disable CS1591
public class Program
{
public static void Main(string[] args)
public static async Task Main(string[] args)
{
var host = CreateHostBuilder(args).Build();

using (var scope = host.Services.CreateScope())
using (var context = scope.ServiceProvider.GetService<AppDbContext>())
using var scope = host.Services.CreateScope();
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<AppDbContext>();
await SeedData.Seed(context);
}
catch (Exception ex)
{
context.Database.EnsureCreated();
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occured during Seeding Data");
}

host.Run();
await host.RunAsync();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Expand Down
9 changes: 3 additions & 6 deletions src/Supermarket.API/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,10 @@ namespace Supermarket.API
{
public class Startup
{
public IConfiguration Configuration { get; }

public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
private readonly IConfiguration Configuration;

public Startup(IConfiguration configuration) => Configuration = configuration;

public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
Expand Down
16 changes: 8 additions & 8 deletions src/Supermarket.API/Supermarket.API.csproj
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DocumentationFile>bin\Debug\netcoreapp3.1\Supermarket.API.xml</DocumentationFile>
<OutputPath>bin\Debug\netcoreapp3.1\</OutputPath>
<DocumentationFile>bin\Debug\net5.0\Supermarket.API.xml</DocumentationFile>
<OutputPath>bin\Debug\net5.0</OutputPath>
<NoWarn>1701;1702;1591;</NoWarn>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="AutoMapper" Version="9.0.0" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="3.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.1.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0-rc5" />
<PackageReference Include="AutoMapper" Version="10.1.1" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="5.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.4" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>

</Project>
6 changes: 3 additions & 3 deletions src/Supermarket.API/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
"Default": "Information",
"Microsoft": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

0 comments on commit 3d05025

Please sign in to comment.