From 5e2c2b8296e943273c84cd68cc5a6fee39f27094 Mon Sep 17 00:00:00 2001 From: BabychMaksym Date: Thu, 28 Mar 2024 22:20:39 +0200 Subject: [PATCH 1/4] Add HomeWork 22 --- HomeWork22/HomeWork22.sln | 25 +++ HomeWork22/HomeWork22/App.cs | 28 +++ .../HomeWork22/Datas/ApplicatDbContext.cs | 26 +++ .../Datas/ApplicatDbContextFactory.cs | 31 ++++ .../Datas/Entities/CostumerEntity.cs | 11 ++ .../HomeWork22/Datas/Entities/OrderEntity.cs | 11 ++ .../Datas/Entities/OrderItemEntity.cs | 12 ++ .../Datas/Entities/ProductEntity.cs | 11 ++ .../CostumerEntityConfiguration.cs | 23 +++ .../OrderEntityConfiguration.cs | 21 +++ .../OrderItemEntityConguration.cs | 30 ++++ .../ProductEntityConfiguration.cs | 23 +++ HomeWork22/HomeWork22/HomeWork22.csproj | 38 +++++ .../20240328193537_CreateNew.Designer.cs | 161 ++++++++++++++++++ .../Migrations/20240328193537_CreateNew.cs | 119 +++++++++++++ .../ApplicatDbContextModelSnapshot.cs | 158 +++++++++++++++++ HomeWork22/HomeWork22/Models/Costumer.cs | 10 ++ HomeWork22/HomeWork22/Models/Order.cs | 9 + HomeWork22/HomeWork22/Models/OrderItem.cs | 9 + HomeWork22/HomeWork22/Models/Product.cs | 9 + HomeWork22/HomeWork22/Program.cs | 59 +++++++ .../Abstractions/ICostumerRepository.cs | 10 ++ .../Abstractions/IOrderRepository.cs | 12 ++ .../Abstractions/IProductRepository.cs | 10 ++ .../Repositories/CostumerRepository.cs | 41 +++++ .../Repositories/OrderRepository.cs | 60 +++++++ .../Repositories/ProductRepository.cs | 36 ++++ .../Services/Abstracts/ICostumerService.cs | 10 ++ .../Services/Abstracts/IOrderService.cs | 11 ++ .../Services/Abstracts/IProductService.cs | 10 ++ .../HomeWork22/Services/CostumerService.cs | 47 +++++ .../HomeWork22/Services/OrderService.cs | 85 +++++++++ .../HomeWork22/Services/ProductService.cs | 45 +++++ HomeWork22/HomeWork22/config.json | 9 + 34 files changed, 1210 insertions(+) create mode 100644 HomeWork22/HomeWork22.sln create mode 100644 HomeWork22/HomeWork22/App.cs create mode 100644 HomeWork22/HomeWork22/Datas/ApplicatDbContext.cs create mode 100644 HomeWork22/HomeWork22/Datas/ApplicatDbContextFactory.cs create mode 100644 HomeWork22/HomeWork22/Datas/Entities/CostumerEntity.cs create mode 100644 HomeWork22/HomeWork22/Datas/Entities/OrderEntity.cs create mode 100644 HomeWork22/HomeWork22/Datas/Entities/OrderItemEntity.cs create mode 100644 HomeWork22/HomeWork22/Datas/Entities/ProductEntity.cs create mode 100644 HomeWork22/HomeWork22/Datas/EntitiesConfigurations/CostumerEntityConfiguration.cs create mode 100644 HomeWork22/HomeWork22/Datas/EntitiesConfigurations/OrderEntityConfiguration.cs create mode 100644 HomeWork22/HomeWork22/Datas/EntitiesConfigurations/OrderItemEntityConguration.cs create mode 100644 HomeWork22/HomeWork22/Datas/EntitiesConfigurations/ProductEntityConfiguration.cs create mode 100644 HomeWork22/HomeWork22/HomeWork22.csproj create mode 100644 HomeWork22/HomeWork22/Migrations/20240328193537_CreateNew.Designer.cs create mode 100644 HomeWork22/HomeWork22/Migrations/20240328193537_CreateNew.cs create mode 100644 HomeWork22/HomeWork22/Migrations/ApplicatDbContextModelSnapshot.cs create mode 100644 HomeWork22/HomeWork22/Models/Costumer.cs create mode 100644 HomeWork22/HomeWork22/Models/Order.cs create mode 100644 HomeWork22/HomeWork22/Models/OrderItem.cs create mode 100644 HomeWork22/HomeWork22/Models/Product.cs create mode 100644 HomeWork22/HomeWork22/Program.cs create mode 100644 HomeWork22/HomeWork22/Repositories/Abstractions/ICostumerRepository.cs create mode 100644 HomeWork22/HomeWork22/Repositories/Abstractions/IOrderRepository.cs create mode 100644 HomeWork22/HomeWork22/Repositories/Abstractions/IProductRepository.cs create mode 100644 HomeWork22/HomeWork22/Repositories/CostumerRepository.cs create mode 100644 HomeWork22/HomeWork22/Repositories/OrderRepository.cs create mode 100644 HomeWork22/HomeWork22/Repositories/ProductRepository.cs create mode 100644 HomeWork22/HomeWork22/Services/Abstracts/ICostumerService.cs create mode 100644 HomeWork22/HomeWork22/Services/Abstracts/IOrderService.cs create mode 100644 HomeWork22/HomeWork22/Services/Abstracts/IProductService.cs create mode 100644 HomeWork22/HomeWork22/Services/CostumerService.cs create mode 100644 HomeWork22/HomeWork22/Services/OrderService.cs create mode 100644 HomeWork22/HomeWork22/Services/ProductService.cs create mode 100644 HomeWork22/HomeWork22/config.json diff --git a/HomeWork22/HomeWork22.sln b/HomeWork22/HomeWork22.sln new file mode 100644 index 0000000..9490613 --- /dev/null +++ b/HomeWork22/HomeWork22.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.8.34525.116 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HomeWork22", "HomeWork22\HomeWork22.csproj", "{CFCCD84A-B798-4733-978A-B3098BB61F1F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CFCCD84A-B798-4733-978A-B3098BB61F1F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CFCCD84A-B798-4733-978A-B3098BB61F1F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CFCCD84A-B798-4733-978A-B3098BB61F1F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CFCCD84A-B798-4733-978A-B3098BB61F1F}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {7D596900-7DD0-4AB6-A8B6-681469160DEE} + EndGlobalSection +EndGlobal diff --git a/HomeWork22/HomeWork22/App.cs b/HomeWork22/HomeWork22/App.cs new file mode 100644 index 0000000..ccb1c00 --- /dev/null +++ b/HomeWork22/HomeWork22/App.cs @@ -0,0 +1,28 @@ +using HomeWork22.Services.Abstracts; + +namespace HomeWork22 +{ + internal class App + { + private readonly IOrderService _orderService; + private readonly ICostumerService _costumerService; + private readonly IProductService _productService; + public App(IProductService productService, ICostumerService costumerService, IOrderService orderService) + { + _costumerService = costumerService; + _orderService = orderService; + _productService = productService; + } + public async Task StartAsync() + { + var idConstumer = await _costumerService.AddCostumerAsync("Max", "Valerin"); + + var costumer = await _costumerService.GetCostumerAsync(idConstumer); + + Console.WriteLine(costumer.Fullname); + + //await _orderService.AddOrderAsync(); + var idProduct = await _productService.AddProductAsync("Limon", 15.25); + } + } +} diff --git a/HomeWork22/HomeWork22/Datas/ApplicatDbContext.cs b/HomeWork22/HomeWork22/Datas/ApplicatDbContext.cs new file mode 100644 index 0000000..0c0fa47 --- /dev/null +++ b/HomeWork22/HomeWork22/Datas/ApplicatDbContext.cs @@ -0,0 +1,26 @@ +using HomeWork22.Datas.Entities; +using HomeWork22.Datas.EntitiesConfigurations; +using Microsoft.EntityFrameworkCore; + +namespace HomeWork22.Datas +{ + internal class ApplicatDbContext : DbContext + { + public ApplicatDbContext(DbContextOptions options) + : base(options) + {} + + public DbSet Costumers { get; set; } = null!; + public DbSet Orders { get; set; } = null!; + public DbSet OrderItems { get; set; } = null!; + public DbSet Products { get; set; } = null!; + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.ApplyConfiguration(new CostumerEntityConfiguration()); + modelBuilder.ApplyConfiguration(new OrderEntityConfiguration()); + modelBuilder.ApplyConfiguration(new OrderItemEntityConguration()); + modelBuilder.ApplyConfiguration(new ProductEntityConfiguration()); + } + } +} diff --git a/HomeWork22/HomeWork22/Datas/ApplicatDbContextFactory.cs b/HomeWork22/HomeWork22/Datas/ApplicatDbContextFactory.cs new file mode 100644 index 0000000..74ca62e --- /dev/null +++ b/HomeWork22/HomeWork22/Datas/ApplicatDbContextFactory.cs @@ -0,0 +1,31 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; +using Microsoft.Extensions.Configuration; + +namespace HomeWork22.Datas +{ + internal class ApplicatDbContextFactory : IDesignTimeDbContextFactory + { + public ApplicatDbContext CreateDbContext(string[] args) + { + var optionalBuilder = new DbContextOptionsBuilder(); + + var builder = new ConfigurationBuilder(); + builder.SetBasePath(Directory.GetCurrentDirectory()); + + var config = builder + .AddJsonFile("config.json") + .Build(); + + var connectionString = config.GetConnectionString("DefaultConnection"); + optionalBuilder + .UseSqlServer(connectionString, option => + option + .CommandTimeout((int)TimeSpan + .FromMinutes(10) + .TotalSeconds)); + + return new ApplicatDbContext(optionalBuilder.Options); + } + } +} diff --git a/HomeWork22/HomeWork22/Datas/Entities/CostumerEntity.cs b/HomeWork22/HomeWork22/Datas/Entities/CostumerEntity.cs new file mode 100644 index 0000000..95b733b --- /dev/null +++ b/HomeWork22/HomeWork22/Datas/Entities/CostumerEntity.cs @@ -0,0 +1,11 @@ +namespace HomeWork22.Datas.Entities +{ + internal class CostumerEntity + { + public int Id { get; set; } + public string? FirstName { get; set; } + public string? LastName { get; set; } + + public ICollection Orders { get; set; } = new List(); + } +} diff --git a/HomeWork22/HomeWork22/Datas/Entities/OrderEntity.cs b/HomeWork22/HomeWork22/Datas/Entities/OrderEntity.cs new file mode 100644 index 0000000..69748f5 --- /dev/null +++ b/HomeWork22/HomeWork22/Datas/Entities/OrderEntity.cs @@ -0,0 +1,11 @@ +namespace HomeWork22.Datas.Entities +{ + internal class OrderEntity + { + public int Id { get; set; } + public int CostumerId { get; set; } + public CostumerEntity? Costumer { get; set; } + + public ICollection OrderItems { get; set; } = new List(); + } +} diff --git a/HomeWork22/HomeWork22/Datas/Entities/OrderItemEntity.cs b/HomeWork22/HomeWork22/Datas/Entities/OrderItemEntity.cs new file mode 100644 index 0000000..3361f85 --- /dev/null +++ b/HomeWork22/HomeWork22/Datas/Entities/OrderItemEntity.cs @@ -0,0 +1,12 @@ +namespace HomeWork22.Datas.Entities +{ + internal class OrderItemEntity + { + public int Id { get; set; } + public int Count { get; set; } + public int OrderId { get; set; } + public OrderEntity? Order { get; set; } + public int ProductId { get; set; } + public ProductEntity? Product { get; set; } + } +} diff --git a/HomeWork22/HomeWork22/Datas/Entities/ProductEntity.cs b/HomeWork22/HomeWork22/Datas/Entities/ProductEntity.cs new file mode 100644 index 0000000..23e09a2 --- /dev/null +++ b/HomeWork22/HomeWork22/Datas/Entities/ProductEntity.cs @@ -0,0 +1,11 @@ +namespace HomeWork22.Datas.Entities +{ + internal class ProductEntity + { + public int Id { get; set; } + public string Name { get; set; } = null!; + public double Price { get; set; } + + public ICollection OrderItems { get; set; } = new List(); + } +} diff --git a/HomeWork22/HomeWork22/Datas/EntitiesConfigurations/CostumerEntityConfiguration.cs b/HomeWork22/HomeWork22/Datas/EntitiesConfigurations/CostumerEntityConfiguration.cs new file mode 100644 index 0000000..8ea331a --- /dev/null +++ b/HomeWork22/HomeWork22/Datas/EntitiesConfigurations/CostumerEntityConfiguration.cs @@ -0,0 +1,23 @@ +using HomeWork22.Datas.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace HomeWork22.Datas.EntitiesConfigurations +{ + internal class CostumerEntityConfiguration : IEntityTypeConfiguration + { + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(x => x.Id); + + builder + .Property(p => p.FirstName) + .HasMaxLength(50); + + builder + .Property(p => p.LastName) + .IsRequired() + .HasMaxLength(50); + } + } +} diff --git a/HomeWork22/HomeWork22/Datas/EntitiesConfigurations/OrderEntityConfiguration.cs b/HomeWork22/HomeWork22/Datas/EntitiesConfigurations/OrderEntityConfiguration.cs new file mode 100644 index 0000000..ece0463 --- /dev/null +++ b/HomeWork22/HomeWork22/Datas/EntitiesConfigurations/OrderEntityConfiguration.cs @@ -0,0 +1,21 @@ +using HomeWork22.Datas.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace HomeWork22.Datas.EntitiesConfigurations +{ + internal class OrderEntityConfiguration : IEntityTypeConfiguration + { + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(x => x.Id); + + builder + .HasOne(o => o.Costumer) + .WithMany(m => m.Orders) + .HasForeignKey(o => o.CostumerId) + .OnDelete(DeleteBehavior.Cascade); + + } + } +} diff --git a/HomeWork22/HomeWork22/Datas/EntitiesConfigurations/OrderItemEntityConguration.cs b/HomeWork22/HomeWork22/Datas/EntitiesConfigurations/OrderItemEntityConguration.cs new file mode 100644 index 0000000..1212947 --- /dev/null +++ b/HomeWork22/HomeWork22/Datas/EntitiesConfigurations/OrderItemEntityConguration.cs @@ -0,0 +1,30 @@ +using HomeWork22.Datas.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace HomeWork22.Datas.EntitiesConfigurations +{ + internal class OrderItemEntityConguration : IEntityTypeConfiguration + { + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(x=>x.Id); + + builder + .Property(x => x.Count) + .IsRequired(); + + builder + .HasOne(x => x.Order) + .WithMany(x => x.OrderItems) + .HasForeignKey(x=>x.OrderId) + .OnDelete(DeleteBehavior.Cascade); + + builder + .HasOne(x=>x.Product) + .WithMany(x => x.OrderItems) + .HasForeignKey(x=>x.ProductId) + .OnDelete(DeleteBehavior.Cascade); + } + } +} diff --git a/HomeWork22/HomeWork22/Datas/EntitiesConfigurations/ProductEntityConfiguration.cs b/HomeWork22/HomeWork22/Datas/EntitiesConfigurations/ProductEntityConfiguration.cs new file mode 100644 index 0000000..50a245d --- /dev/null +++ b/HomeWork22/HomeWork22/Datas/EntitiesConfigurations/ProductEntityConfiguration.cs @@ -0,0 +1,23 @@ +using HomeWork22.Datas.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace HomeWork22.Datas.EntitiesConfigurations +{ + internal class ProductEntityConfiguration : IEntityTypeConfiguration + { + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(x=>x.Id); + + builder + .Property(x => x.Name) + .IsRequired() + .HasMaxLength(100); + + builder + .Property(x => x.Price) + .IsRequired(); + } + } +} diff --git a/HomeWork22/HomeWork22/HomeWork22.csproj b/HomeWork22/HomeWork22/HomeWork22.csproj new file mode 100644 index 0000000..34c476b --- /dev/null +++ b/HomeWork22/HomeWork22/HomeWork22.csproj @@ -0,0 +1,38 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + Always + + + + diff --git a/HomeWork22/HomeWork22/Migrations/20240328193537_CreateNew.Designer.cs b/HomeWork22/HomeWork22/Migrations/20240328193537_CreateNew.Designer.cs new file mode 100644 index 0000000..ec2316e --- /dev/null +++ b/HomeWork22/HomeWork22/Migrations/20240328193537_CreateNew.Designer.cs @@ -0,0 +1,161 @@ +// +using HomeWork22.Datas; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace HomeWork22.Migrations +{ + [DbContext(typeof(ApplicatDbContext))] + [Migration("20240328193537_CreateNew")] + partial class CreateNew + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.3") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("HomeWork22.Datas.Entities.CostumerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("FirstName") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("LastName") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.ToTable("Costumers"); + }); + + modelBuilder.Entity("HomeWork22.Datas.Entities.OrderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CostumerId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("CostumerId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("HomeWork22.Datas.Entities.OrderItemEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("OrderId") + .HasColumnType("int"); + + b.Property("ProductId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("OrderId"); + + b.HasIndex("ProductId"); + + b.ToTable("OrderItems"); + }); + + modelBuilder.Entity("HomeWork22.Datas.Entities.ProductEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Products"); + }); + + modelBuilder.Entity("HomeWork22.Datas.Entities.OrderEntity", b => + { + b.HasOne("HomeWork22.Datas.Entities.CostumerEntity", "Costumer") + .WithMany("Orders") + .HasForeignKey("CostumerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Costumer"); + }); + + modelBuilder.Entity("HomeWork22.Datas.Entities.OrderItemEntity", b => + { + b.HasOne("HomeWork22.Datas.Entities.OrderEntity", "Order") + .WithMany("OrderItems") + .HasForeignKey("OrderId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("HomeWork22.Datas.Entities.ProductEntity", "Product") + .WithMany("OrderItems") + .HasForeignKey("ProductId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Order"); + + b.Navigation("Product"); + }); + + modelBuilder.Entity("HomeWork22.Datas.Entities.CostumerEntity", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("HomeWork22.Datas.Entities.OrderEntity", b => + { + b.Navigation("OrderItems"); + }); + + modelBuilder.Entity("HomeWork22.Datas.Entities.ProductEntity", b => + { + b.Navigation("OrderItems"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/HomeWork22/HomeWork22/Migrations/20240328193537_CreateNew.cs b/HomeWork22/HomeWork22/Migrations/20240328193537_CreateNew.cs new file mode 100644 index 0000000..98b2aec --- /dev/null +++ b/HomeWork22/HomeWork22/Migrations/20240328193537_CreateNew.cs @@ -0,0 +1,119 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace HomeWork22.Migrations +{ + /// + public partial class CreateNew : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Costumers", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + FirstName = table.Column(type: "nvarchar(50)", maxLength: 50, nullable: true), + LastName = table.Column(type: "nvarchar(50)", maxLength: 50, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Costumers", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Products", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Name = table.Column(type: "nvarchar(100)", maxLength: 100, nullable: false), + Price = table.Column(type: "float", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Products", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Orders", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + CostumerId = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Orders", x => x.Id); + table.ForeignKey( + name: "FK_Orders_Costumers_CostumerId", + column: x => x.CostumerId, + principalTable: "Costumers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "OrderItems", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Count = table.Column(type: "int", nullable: false), + OrderId = table.Column(type: "int", nullable: false), + ProductId = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OrderItems", x => x.Id); + table.ForeignKey( + name: "FK_OrderItems_Orders_OrderId", + column: x => x.OrderId, + principalTable: "Orders", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_OrderItems_Products_ProductId", + column: x => x.ProductId, + principalTable: "Products", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_OrderItems_OrderId", + table: "OrderItems", + column: "OrderId"); + + migrationBuilder.CreateIndex( + name: "IX_OrderItems_ProductId", + table: "OrderItems", + column: "ProductId"); + + migrationBuilder.CreateIndex( + name: "IX_Orders_CostumerId", + table: "Orders", + column: "CostumerId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "OrderItems"); + + migrationBuilder.DropTable( + name: "Orders"); + + migrationBuilder.DropTable( + name: "Products"); + + migrationBuilder.DropTable( + name: "Costumers"); + } + } +} diff --git a/HomeWork22/HomeWork22/Migrations/ApplicatDbContextModelSnapshot.cs b/HomeWork22/HomeWork22/Migrations/ApplicatDbContextModelSnapshot.cs new file mode 100644 index 0000000..e85e636 --- /dev/null +++ b/HomeWork22/HomeWork22/Migrations/ApplicatDbContextModelSnapshot.cs @@ -0,0 +1,158 @@ +// +using HomeWork22.Datas; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace HomeWork22.Migrations +{ + [DbContext(typeof(ApplicatDbContext))] + partial class ApplicatDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.3") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("HomeWork22.Datas.Entities.CostumerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("FirstName") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("LastName") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.ToTable("Costumers"); + }); + + modelBuilder.Entity("HomeWork22.Datas.Entities.OrderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CostumerId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("CostumerId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("HomeWork22.Datas.Entities.OrderItemEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("OrderId") + .HasColumnType("int"); + + b.Property("ProductId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("OrderId"); + + b.HasIndex("ProductId"); + + b.ToTable("OrderItems"); + }); + + modelBuilder.Entity("HomeWork22.Datas.Entities.ProductEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Products"); + }); + + modelBuilder.Entity("HomeWork22.Datas.Entities.OrderEntity", b => + { + b.HasOne("HomeWork22.Datas.Entities.CostumerEntity", "Costumer") + .WithMany("Orders") + .HasForeignKey("CostumerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Costumer"); + }); + + modelBuilder.Entity("HomeWork22.Datas.Entities.OrderItemEntity", b => + { + b.HasOne("HomeWork22.Datas.Entities.OrderEntity", "Order") + .WithMany("OrderItems") + .HasForeignKey("OrderId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("HomeWork22.Datas.Entities.ProductEntity", "Product") + .WithMany("OrderItems") + .HasForeignKey("ProductId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Order"); + + b.Navigation("Product"); + }); + + modelBuilder.Entity("HomeWork22.Datas.Entities.CostumerEntity", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("HomeWork22.Datas.Entities.OrderEntity", b => + { + b.Navigation("OrderItems"); + }); + + modelBuilder.Entity("HomeWork22.Datas.Entities.ProductEntity", b => + { + b.Navigation("OrderItems"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/HomeWork22/HomeWork22/Models/Costumer.cs b/HomeWork22/HomeWork22/Models/Costumer.cs new file mode 100644 index 0000000..2975082 --- /dev/null +++ b/HomeWork22/HomeWork22/Models/Costumer.cs @@ -0,0 +1,10 @@ +namespace HomeWork22.Models +{ + internal class Costumer + { + public int Id { get; set; } + public string? Lastname { get; set; } + public string? Firstname { get; set; } + public string? Fullname { get; set; } + } +} diff --git a/HomeWork22/HomeWork22/Models/Order.cs b/HomeWork22/HomeWork22/Models/Order.cs new file mode 100644 index 0000000..2fd607d --- /dev/null +++ b/HomeWork22/HomeWork22/Models/Order.cs @@ -0,0 +1,9 @@ +namespace HomeWork22.Models +{ + internal class Order + { + public int Id { get; set; } + public Costumer? Costumer { get; set; } + public IEnumerable? OrderItem { get; set; } + } +} diff --git a/HomeWork22/HomeWork22/Models/OrderItem.cs b/HomeWork22/HomeWork22/Models/OrderItem.cs new file mode 100644 index 0000000..fb3b387 --- /dev/null +++ b/HomeWork22/HomeWork22/Models/OrderItem.cs @@ -0,0 +1,9 @@ +namespace HomeWork22.Models +{ + internal class OrderItem + { + public int Count { get; set; } + public int ProductId { get; set; } + public Product? Product { get; set; } + } +} diff --git a/HomeWork22/HomeWork22/Models/Product.cs b/HomeWork22/HomeWork22/Models/Product.cs new file mode 100644 index 0000000..0050dc9 --- /dev/null +++ b/HomeWork22/HomeWork22/Models/Product.cs @@ -0,0 +1,9 @@ +namespace HomeWork22.Models +{ + internal class Product + { + public int Id { get; set; } + public string Name { get; set; } = null!; + public double Price { get; set; } + } +} diff --git a/HomeWork22/HomeWork22/Program.cs b/HomeWork22/HomeWork22/Program.cs new file mode 100644 index 0000000..d0b5163 --- /dev/null +++ b/HomeWork22/HomeWork22/Program.cs @@ -0,0 +1,59 @@ +using HomeWork22.Datas; +using HomeWork22.Repositories; +using HomeWork22.Repositories.Abstractions; +using HomeWork22.Services; +using HomeWork22.Services.Abstracts; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace HomeWork22 +{ + class Program + { + static async Task Main(string[] args) + { + void ConfigureService(ServiceCollection serviceCollection, IConfiguration configuration) + { + var connectionString = configuration.GetConnectionString("DefaultConnection"); + serviceCollection + .AddDbContextFactory(option => + option + .UseSqlServer(connectionString)); + // serviceColection.addwraper + + serviceCollection + .AddLogging(login => login.AddConsole()) + .AddTransient() + .AddTransient() + .AddTransient() + .AddTransient() + .AddTransient() + .AddTransient() + .AddTransient(); + } + + IConfiguration configuration = new ConfigurationBuilder() + .AddJsonFile("config.json") + .Build(); + + var serviceCollection = new ServiceCollection(); + ConfigureService (serviceCollection, configuration); + var provider = serviceCollection.BuildServiceProvider(); + + var isNeedMigration = configuration + .GetSection("Migration") + .GetSection("IsNeedMigration"); + + if (bool.Parse(isNeedMigration.Value!)) + { + var dbContext = provider.GetService(); + await dbContext!.Database.MigrateAsync(); + } + + var app = provider.GetService(); + await app!.StartAsync(); + } + } +} diff --git a/HomeWork22/HomeWork22/Repositories/Abstractions/ICostumerRepository.cs b/HomeWork22/HomeWork22/Repositories/Abstractions/ICostumerRepository.cs new file mode 100644 index 0000000..6b5beb0 --- /dev/null +++ b/HomeWork22/HomeWork22/Repositories/Abstractions/ICostumerRepository.cs @@ -0,0 +1,10 @@ +using HomeWork22.Datas.Entities; + +namespace HomeWork22.Repositories.Abstractions +{ + internal interface ICostumerRepository + { + public Task AddCostumer(string lastname, string firstname); + public Task GetCostumer(int id); + } +} diff --git a/HomeWork22/HomeWork22/Repositories/Abstractions/IOrderRepository.cs b/HomeWork22/HomeWork22/Repositories/Abstractions/IOrderRepository.cs new file mode 100644 index 0000000..082a4bd --- /dev/null +++ b/HomeWork22/HomeWork22/Repositories/Abstractions/IOrderRepository.cs @@ -0,0 +1,12 @@ +using HomeWork22.Datas.Entities; +using HomeWork22.Models; + +namespace HomeWork22.Repositories.Abstractions +{ + internal interface IOrderRepository + { + public Task AddOrderAsync(int id, List orderItemList); + public Task GetOrder(int id); + public Task?> GetOrderByCostumerId(int id); + } +} diff --git a/HomeWork22/HomeWork22/Repositories/Abstractions/IProductRepository.cs b/HomeWork22/HomeWork22/Repositories/Abstractions/IProductRepository.cs new file mode 100644 index 0000000..a4c1f13 --- /dev/null +++ b/HomeWork22/HomeWork22/Repositories/Abstractions/IProductRepository.cs @@ -0,0 +1,10 @@ +using HomeWork22.Datas.Entities; + +namespace HomeWork22.Repositories.Abstractions +{ + internal interface IProductRepository + { + public Task AddProduct(string name, double price); + public Task GetProduct(int id); + } +} diff --git a/HomeWork22/HomeWork22/Repositories/CostumerRepository.cs b/HomeWork22/HomeWork22/Repositories/CostumerRepository.cs new file mode 100644 index 0000000..dbc6fd5 --- /dev/null +++ b/HomeWork22/HomeWork22/Repositories/CostumerRepository.cs @@ -0,0 +1,41 @@ +using HomeWork22.Datas; +using HomeWork22.Datas.Entities; +using HomeWork22.Repositories.Abstractions; +using Microsoft.EntityFrameworkCore; + +namespace HomeWork22.Repositories +{ + internal class CostumerRepository : ICostumerRepository + { + private readonly ApplicatDbContext _dbContext; + + public CostumerRepository(ApplicatDbContext dbContext) + { + _dbContext = dbContext; + } + + public async Task AddCostumer(string lastname, string firstname) + { + var costumer = new CostumerEntity() + { + FirstName = firstname, + LastName = lastname + }; + + var costm = await _dbContext.AddAsync(costumer); + await _dbContext.SaveChangesAsync(); + + return costm.Entity.Id; + } + + //public async Task UpdateCostumers() + //{ + + //} + + public async Task GetCostumer(int id) + { + return await _dbContext.Costumers.FirstOrDefaultAsync(c=>c.Id == id); + } + } +} diff --git a/HomeWork22/HomeWork22/Repositories/OrderRepository.cs b/HomeWork22/HomeWork22/Repositories/OrderRepository.cs new file mode 100644 index 0000000..dfbb2c1 --- /dev/null +++ b/HomeWork22/HomeWork22/Repositories/OrderRepository.cs @@ -0,0 +1,60 @@ +using HomeWork22.Datas; +using HomeWork22.Datas.Entities; +using HomeWork22.Models; +using HomeWork22.Repositories.Abstractions; +using Microsoft.EntityFrameworkCore; + +namespace HomeWork22.Repositories +{ + internal class OrderRepository : IOrderRepository + { + private readonly ApplicatDbContext _dbContext; + + public OrderRepository(ApplicatDbContext dbContext) + { + _dbContext = dbContext; + } + + public async Task AddOrderAsync(int id, List orderItemList) + { + var order = await _dbContext + .Orders + .AddAsync(new OrderEntity() + { + CostumerId = id, + }); + + await _dbContext + .OrderItems + .AddRangeAsync(orderItemList.Select(s => + new OrderItemEntity() + { + Count = s.Count, + OrderId = order.Entity.Id, + ProductId = s.ProductId, + } + )); + + await _dbContext.SaveChangesAsync(); + + return order.Entity.Id; + } + + public async Task GetOrder(int id) + { + return await _dbContext + .Orders + .Include(i => i.OrderItems) + .FirstOrDefaultAsync(x=>x.Id == id); + } + + public async Task?> GetOrderByCostumerId(int id) + { + return await _dbContext + .Orders + .Include(x=>x.OrderItems) + .Where(x=>x.CostumerId==id) + .ToListAsync(); + } + } +} diff --git a/HomeWork22/HomeWork22/Repositories/ProductRepository.cs b/HomeWork22/HomeWork22/Repositories/ProductRepository.cs new file mode 100644 index 0000000..3e5c4f4 --- /dev/null +++ b/HomeWork22/HomeWork22/Repositories/ProductRepository.cs @@ -0,0 +1,36 @@ +using HomeWork22.Datas; +using HomeWork22.Datas.Entities; +using HomeWork22.Repositories.Abstractions; +using Microsoft.EntityFrameworkCore; + +namespace HomeWork22.Repositories +{ + internal class ProductRepository : IProductRepository + { + private readonly ApplicatDbContext _dbContext; + + public ProductRepository(ApplicatDbContext dbContext) + { + _dbContext = dbContext; + } + + public async Task AddProduct(string name, double price) + { + var product = new ProductEntity() + { + Name = name, + Price = price + }; + + var products = await _dbContext.Products.AddAsync(product); + await _dbContext.SaveChangesAsync(); + + return products.Entity.Id; + } + + public async Task GetProduct(int id) + { + return await _dbContext.Products.FirstOrDefaultAsync(consumers => consumers.Id == id); + } + } +} diff --git a/HomeWork22/HomeWork22/Services/Abstracts/ICostumerService.cs b/HomeWork22/HomeWork22/Services/Abstracts/ICostumerService.cs new file mode 100644 index 0000000..9c94961 --- /dev/null +++ b/HomeWork22/HomeWork22/Services/Abstracts/ICostumerService.cs @@ -0,0 +1,10 @@ +using HomeWork22.Models; + +namespace HomeWork22.Services.Abstracts +{ + internal interface ICostumerService + { + public Task AddCostumerAsync(string lastname, string firstname); + public Task GetCostumerAsync(int id); + } +} diff --git a/HomeWork22/HomeWork22/Services/Abstracts/IOrderService.cs b/HomeWork22/HomeWork22/Services/Abstracts/IOrderService.cs new file mode 100644 index 0000000..799c9f1 --- /dev/null +++ b/HomeWork22/HomeWork22/Services/Abstracts/IOrderService.cs @@ -0,0 +1,11 @@ +using HomeWork22.Models; + +namespace HomeWork22.Services.Abstracts +{ + internal interface IOrderService + { + public Task AddOrderAsync(int costumerId, List orderItems); + public Task GetOrderAsync(int id); + public Task> GetOrderByCostumerId(int id); + } +} diff --git a/HomeWork22/HomeWork22/Services/Abstracts/IProductService.cs b/HomeWork22/HomeWork22/Services/Abstracts/IProductService.cs new file mode 100644 index 0000000..5d83389 --- /dev/null +++ b/HomeWork22/HomeWork22/Services/Abstracts/IProductService.cs @@ -0,0 +1,10 @@ +using HomeWork22.Models; + +namespace HomeWork22.Services.Abstracts +{ + internal interface IProductService + { + public Task AddProductAsync(string name, double price); + public Task GetProductAsync(int id); + } +} diff --git a/HomeWork22/HomeWork22/Services/CostumerService.cs b/HomeWork22/HomeWork22/Services/CostumerService.cs new file mode 100644 index 0000000..f079b55 --- /dev/null +++ b/HomeWork22/HomeWork22/Services/CostumerService.cs @@ -0,0 +1,47 @@ +using HomeWork22.Models; +using HomeWork22.Repositories.Abstractions; +using HomeWork22.Services.Abstracts; +using Microsoft.Extensions.Logging; + +namespace HomeWork22.Services +{ + internal class CostumerService : ICostumerService + { + private readonly ICostumerRepository _costumerRepository; + private readonly ILogger _logger; + + public CostumerService(ICostumerRepository costumerRepository, ILogger logger) + { + _costumerRepository = costumerRepository; + _logger = logger; + } + + public async Task AddCostumerAsync(string lastname, string firstname) + { + var id = await _costumerRepository.AddCostumer(lastname, firstname); + + _logger.LogInformation($"Succesfull create costumer with id: {id}"); + + return id; + } + + public async Task GetCostumerAsync(int id) + { + var costumerEntity = await _costumerRepository.GetCostumer(id); + + if (costumerEntity is null) + { + _logger.LogWarning($"Costumer is not founded with id: {id}"); + return null!; + } + + return new Costumer() + { + Id = costumerEntity.Id, + Firstname = costumerEntity.FirstName, + Lastname = costumerEntity.LastName, + Fullname = $"{costumerEntity.FirstName} {costumerEntity.LastName}", + }; + } + } +} diff --git a/HomeWork22/HomeWork22/Services/OrderService.cs b/HomeWork22/HomeWork22/Services/OrderService.cs new file mode 100644 index 0000000..241103e --- /dev/null +++ b/HomeWork22/HomeWork22/Services/OrderService.cs @@ -0,0 +1,85 @@ +using HomeWork22.Models; +using HomeWork22.Repositories.Abstractions; +using HomeWork22.Services.Abstracts; +using Microsoft.Extensions.Logging; + +namespace HomeWork22.Services +{ + internal class OrderService : IOrderService + { + private readonly IOrderRepository _orderRepository; + private readonly ILogger _logger; + + public OrderService(IOrderRepository orderRepository, ILogger logger) + { + _orderRepository = orderRepository; + _logger = logger; + } + + public async Task AddOrderAsync(int costumerId, List orderItems) + { + var id = await _orderRepository.AddOrderAsync(costumerId, orderItems); + + _logger.LogInformation($"Order seccusfull created with id {id}"); + + return id; + } + + public async Task GetOrderAsync(int id) + { + var order = await _orderRepository.GetOrder(id); + + if (order is null) + { + _logger.LogWarning($"Order don`t finded with id {id}"); + return null!; + } + + return new Order() + { + Id = order.Id, + + OrderItem = order.OrderItems.Select(s => new OrderItem() + { + Count = s.Count, + ProductId = s.ProductId, + + Product = new Product() + { + Id = s.Product.Id, + Name = s.Product.Name, + Price = s.Product.Price, + } + }) + }; + } + + public async Task> GetOrderByCostumerId(int id) + { + var order = await _orderRepository.GetOrderByCostumerId(id); + + if (order is null) + { + _logger.LogWarning($"Order not founded with id {id}"); + + return null!; + } + + return order.Select(s => new Order() + { + Id = s.Id, + OrderItem = s.OrderItems.Select(r => new OrderItem() + { + Count = r.Count, + ProductId = r.ProductId, + Product = new Product() + { + Id = r.Product.Id, + Name = r.Product.Name, + Price = r.Product.Price, + } + }) + }).ToList(); + } + } +} diff --git a/HomeWork22/HomeWork22/Services/ProductService.cs b/HomeWork22/HomeWork22/Services/ProductService.cs new file mode 100644 index 0000000..2fc3633 --- /dev/null +++ b/HomeWork22/HomeWork22/Services/ProductService.cs @@ -0,0 +1,45 @@ +using HomeWork22.Models; +using HomeWork22.Repositories.Abstractions; +using HomeWork22.Services.Abstracts; +using Microsoft.Extensions.Logging; + +namespace HomeWork22.Services +{ + internal class ProductService : IProductService + { + private readonly IProductRepository _productRepository; + private readonly ILogger _logger; + public ProductService(IProductRepository productRepository, ILogger logger) + { + _productRepository = productRepository; + _logger = logger; + } + + public async Task AddProductAsync(string name, double price) + { + var id = await _productRepository.AddProduct(name, price); + + _logger.LogInformation($"Product succesfull create with id: {id}"); + + return id; + } + + public async Task GetProductAsync(int id) + { + var product = await _productRepository.GetProduct(id); + + if (product is null) + { + _logger.LogWarning("Product with this id don`t exist"); + return null!; + } + + return new Product() + { + Id = product.Id, + Name = product.Name, + Price = product.Price, + }; + } + } +} diff --git a/HomeWork22/HomeWork22/config.json b/HomeWork22/HomeWork22/config.json new file mode 100644 index 0000000..e2c10b5 --- /dev/null +++ b/HomeWork22/HomeWork22/config.json @@ -0,0 +1,9 @@ +{ + "Migration": { + "IsNeedMigration": true + }, + "ConnectionStrings": { + "DefaultConnection": "Server=127.0.0.1,1434;Database=AdventureWorks;User ID=sa;Password=1My_password;TrustServerCertificate=true" + } + +} \ No newline at end of file From 1e261a78641364aba56a3183f5731b1fc53bba45 Mon Sep 17 00:00:00 2001 From: BabychMaksym Date: Sat, 30 Mar 2024 20:15:51 +0200 Subject: [PATCH 2/4] add HomeWork 22 --- HomeWork22/HomeWork22/App.cs | 60 +++++++++++++++-- .../HomeWork22/Datas/ApplicatDbContext.cs | 1 + HomeWork22/HomeWork22/Dtos/PageDto.cs | 8 +++ HomeWork22/HomeWork22/Dtos/RequestPage.cs | 12 ++++ HomeWork22/HomeWork22/Dtos/ResponsPage.cs | 26 +++++++ ...s => 20240329172908_CreateMig.Designer.cs} | 17 +++-- ...eateNew.cs => 20240329172908_CreateMig.cs} | 21 +++--- .../ApplicatDbContextModelSnapshot.cs | 13 ++-- HomeWork22/HomeWork22/Program.cs | 6 +- .../Abstractions/ICostumerRepository.cs | 9 ++- .../Abstractions/IOrderRepository.cs | 2 + .../Abstractions/IProductRepository.cs | 12 +++- .../Repositories/CostumerRepository.cs | 38 ++++++++--- .../Repositories/OrderRepository.cs | 43 ++++++++---- .../Repositories/ProductRepository.cs | 44 ++++++++++-- .../Services/Abstracts/BaseDataService.cs | 67 +++++++++++++++++++ .../Services/Abstracts/IBaseDataService.cs | 6 ++ .../Services/Abstracts/ICostumerService.cs | 5 ++ .../Services/Abstracts/IOrderService.cs | 2 + .../Services/Abstracts/IProductService.cs | 6 +- .../HomeWork22/Services/CostumerService.cs | 52 +++++++++++--- .../HomeWork22/Services/OrderService.cs | 50 ++++++++++++-- .../HomeWork22/Services/ProductService.cs | 58 +++++++++++++--- .../Wrappers/Abstracts/IDbContextWrapper.cs | 12 ++++ .../HomeWork22/Wrappers/DbContextWrapper.cs | 24 +++++++ 25 files changed, 508 insertions(+), 86 deletions(-) create mode 100644 HomeWork22/HomeWork22/Dtos/PageDto.cs create mode 100644 HomeWork22/HomeWork22/Dtos/RequestPage.cs create mode 100644 HomeWork22/HomeWork22/Dtos/ResponsPage.cs rename HomeWork22/HomeWork22/Migrations/{20240328193537_CreateNew.Designer.cs => 20240329172908_CreateMig.Designer.cs} (88%) rename HomeWork22/HomeWork22/Migrations/{20240328193537_CreateNew.cs => 20240329172908_CreateMig.cs} (92%) create mode 100644 HomeWork22/HomeWork22/Services/Abstracts/BaseDataService.cs create mode 100644 HomeWork22/HomeWork22/Services/Abstracts/IBaseDataService.cs create mode 100644 HomeWork22/HomeWork22/Wrappers/Abstracts/IDbContextWrapper.cs create mode 100644 HomeWork22/HomeWork22/Wrappers/DbContextWrapper.cs diff --git a/HomeWork22/HomeWork22/App.cs b/HomeWork22/HomeWork22/App.cs index ccb1c00..0ce1765 100644 --- a/HomeWork22/HomeWork22/App.cs +++ b/HomeWork22/HomeWork22/App.cs @@ -1,4 +1,6 @@ -using HomeWork22.Services.Abstracts; +using HomeWork22.Dtos; +using HomeWork22.Models; +using HomeWork22.Services.Abstracts; namespace HomeWork22 { @@ -15,14 +17,60 @@ public App(IProductService productService, ICostumerService costumerService, IOr } public async Task StartAsync() { - var idConstumer = await _costumerService.AddCostumerAsync("Max", "Valerin"); + var idConstumer = await _costumerService.AddCostumerAsync("Max", "Babych"); var costumer = await _costumerService.GetCostumerAsync(idConstumer); - Console.WriteLine(costumer.Fullname); + costumer = await _costumerService.UpdateCostumerAsync(idConstumer, "Oleg"); - //await _orderService.AddOrderAsync(); - var idProduct = await _productService.AddProductAsync("Limon", 15.25); - } + var idLimon = await _productService.AddProductAsync("Limon", 15.25); + + var idOrange = await _productService.AddProductAsync("Orange", 10.50); + + await _productService.UpdataProductAsync(idLimon, price: 11); + + var productLimon = await _productService.GetProductAsync(idLimon); + + var productOrange = await _productService.GetProductAsync(idOrange); + + List orderItems = new List() + { + new OrderItem() + { + Count = 5, + Product = productLimon, + ProductId = productLimon.Id, + }, + new OrderItem() + { + Count = 10, + Product = productOrange, + ProductId = productOrange.Id, + } + }; + + var idOrder = await _orderService.AddOrderAsync(idConstumer, orderItems); + + var order = await _orderService.GetOrderAsync(idOrder); + + var request = new RequestPage() + { + Name = "", + PageNamber = 1, + PageSize = 20, + PriceMax = 10, + PriceMin = 5, + }; + + await _productService.GetViewProductListAsync(request); + + await _orderService.DeleteOrderAsync(idOrder); + + await _costumerService.DeleteCostumerAsync(idConstumer); + + await _productService.DeleteProduct(idLimon); + + await _productService.DeleteProduct(idOrange); + } } } diff --git a/HomeWork22/HomeWork22/Datas/ApplicatDbContext.cs b/HomeWork22/HomeWork22/Datas/ApplicatDbContext.cs index 0c0fa47..09bc5ea 100644 --- a/HomeWork22/HomeWork22/Datas/ApplicatDbContext.cs +++ b/HomeWork22/HomeWork22/Datas/ApplicatDbContext.cs @@ -21,6 +21,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.ApplyConfiguration(new OrderEntityConfiguration()); modelBuilder.ApplyConfiguration(new OrderItemEntityConguration()); modelBuilder.ApplyConfiguration(new ProductEntityConfiguration()); + modelBuilder.UseHiLo(); } } } diff --git a/HomeWork22/HomeWork22/Dtos/PageDto.cs b/HomeWork22/HomeWork22/Dtos/PageDto.cs new file mode 100644 index 0000000..02b8664 --- /dev/null +++ b/HomeWork22/HomeWork22/Dtos/PageDto.cs @@ -0,0 +1,8 @@ +namespace HomeWork22.Dtos +{ + internal class PageDto + { + public int PageNamber = 1; + public int PageSize = 20; + } +} diff --git a/HomeWork22/HomeWork22/Dtos/RequestPage.cs b/HomeWork22/HomeWork22/Dtos/RequestPage.cs new file mode 100644 index 0000000..3b6dbdc --- /dev/null +++ b/HomeWork22/HomeWork22/Dtos/RequestPage.cs @@ -0,0 +1,12 @@ +using Microsoft.Identity.Client; + +namespace HomeWork22.Dtos +{ + internal class RequestPage : PageDto + { + public string? Name { get; set; } = string.Empty; + public double PriceMax { get; set; } = 0; + public double PriceMin { get; set;} = 0; + + } +} diff --git a/HomeWork22/HomeWork22/Dtos/ResponsPage.cs b/HomeWork22/HomeWork22/Dtos/ResponsPage.cs new file mode 100644 index 0000000..4bdd91b --- /dev/null +++ b/HomeWork22/HomeWork22/Dtos/ResponsPage.cs @@ -0,0 +1,26 @@ +namespace HomeWork22.Dtos +{ + internal class ResponsPage : PageDto + { + public ResponsPage() + { } + + public int TotalItems => Items.Count; + + public int TotalPages + { + get + { + return (int)Math.Ceiling((double)TotalItems / PageSize); + } + } + + public List Items { get; set; } + public ResponsPage(List items, RequestPage request) + { + Items = items; + PageSize = request.PageSize; + PageNamber = request.PageNamber; + } + } +} diff --git a/HomeWork22/HomeWork22/Migrations/20240328193537_CreateNew.Designer.cs b/HomeWork22/HomeWork22/Migrations/20240329172908_CreateMig.Designer.cs similarity index 88% rename from HomeWork22/HomeWork22/Migrations/20240328193537_CreateNew.Designer.cs rename to HomeWork22/HomeWork22/Migrations/20240329172908_CreateMig.Designer.cs index ec2316e..6f1b031 100644 --- a/HomeWork22/HomeWork22/Migrations/20240328193537_CreateNew.Designer.cs +++ b/HomeWork22/HomeWork22/Migrations/20240329172908_CreateMig.Designer.cs @@ -11,8 +11,8 @@ namespace HomeWork22.Migrations { [DbContext(typeof(ApplicatDbContext))] - [Migration("20240328193537_CreateNew")] - partial class CreateNew + [Migration("20240329172908_CreateMig")] + partial class CreateMig { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) @@ -22,7 +22,10 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .HasAnnotation("ProductVersion", "8.0.3") .HasAnnotation("Relational:MaxIdentifierLength", 128); - SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + SqlServerModelBuilderExtensions.UseHiLo(modelBuilder, "EntityFrameworkHiLoSequence"); + + modelBuilder.HasSequence("EntityFrameworkHiLoSequence") + .IncrementsBy(10); modelBuilder.Entity("HomeWork22.Datas.Entities.CostumerEntity", b => { @@ -30,7 +33,7 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .ValueGeneratedOnAdd() .HasColumnType("int"); - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + SqlServerPropertyBuilderExtensions.UseHiLo(b.Property("Id")); b.Property("FirstName") .HasMaxLength(50) @@ -52,7 +55,7 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .ValueGeneratedOnAdd() .HasColumnType("int"); - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + SqlServerPropertyBuilderExtensions.UseHiLo(b.Property("Id")); b.Property("CostumerId") .HasColumnType("int"); @@ -70,7 +73,7 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .ValueGeneratedOnAdd() .HasColumnType("int"); - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + SqlServerPropertyBuilderExtensions.UseHiLo(b.Property("Id")); b.Property("Count") .HasColumnType("int"); @@ -96,7 +99,7 @@ protected override void BuildTargetModel(ModelBuilder modelBuilder) .ValueGeneratedOnAdd() .HasColumnType("int"); - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + SqlServerPropertyBuilderExtensions.UseHiLo(b.Property("Id")); b.Property("Name") .IsRequired() diff --git a/HomeWork22/HomeWork22/Migrations/20240328193537_CreateNew.cs b/HomeWork22/HomeWork22/Migrations/20240329172908_CreateMig.cs similarity index 92% rename from HomeWork22/HomeWork22/Migrations/20240328193537_CreateNew.cs rename to HomeWork22/HomeWork22/Migrations/20240329172908_CreateMig.cs index 98b2aec..92cb0e7 100644 --- a/HomeWork22/HomeWork22/Migrations/20240328193537_CreateNew.cs +++ b/HomeWork22/HomeWork22/Migrations/20240329172908_CreateMig.cs @@ -5,17 +5,20 @@ namespace HomeWork22.Migrations { /// - public partial class CreateNew : Migration + public partial class CreateMig : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) { + migrationBuilder.CreateSequence( + name: "EntityFrameworkHiLoSequence", + incrementBy: 10); + migrationBuilder.CreateTable( name: "Costumers", columns: table => new { - Id = table.Column(type: "int", nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), + Id = table.Column(type: "int", nullable: false), FirstName = table.Column(type: "nvarchar(50)", maxLength: 50, nullable: true), LastName = table.Column(type: "nvarchar(50)", maxLength: 50, nullable: false) }, @@ -28,8 +31,7 @@ protected override void Up(MigrationBuilder migrationBuilder) name: "Products", columns: table => new { - Id = table.Column(type: "int", nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), + Id = table.Column(type: "int", nullable: false), Name = table.Column(type: "nvarchar(100)", maxLength: 100, nullable: false), Price = table.Column(type: "float", nullable: false) }, @@ -42,8 +44,7 @@ protected override void Up(MigrationBuilder migrationBuilder) name: "Orders", columns: table => new { - Id = table.Column(type: "int", nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), + Id = table.Column(type: "int", nullable: false), CostumerId = table.Column(type: "int", nullable: false) }, constraints: table => @@ -61,8 +62,7 @@ protected override void Up(MigrationBuilder migrationBuilder) name: "OrderItems", columns: table => new { - Id = table.Column(type: "int", nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), + Id = table.Column(type: "int", nullable: false), Count = table.Column(type: "int", nullable: false), OrderId = table.Column(type: "int", nullable: false), ProductId = table.Column(type: "int", nullable: false) @@ -114,6 +114,9 @@ protected override void Down(MigrationBuilder migrationBuilder) migrationBuilder.DropTable( name: "Costumers"); + + migrationBuilder.DropSequence( + name: "EntityFrameworkHiLoSequence"); } } } diff --git a/HomeWork22/HomeWork22/Migrations/ApplicatDbContextModelSnapshot.cs b/HomeWork22/HomeWork22/Migrations/ApplicatDbContextModelSnapshot.cs index e85e636..4569300 100644 --- a/HomeWork22/HomeWork22/Migrations/ApplicatDbContextModelSnapshot.cs +++ b/HomeWork22/HomeWork22/Migrations/ApplicatDbContextModelSnapshot.cs @@ -19,7 +19,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasAnnotation("ProductVersion", "8.0.3") .HasAnnotation("Relational:MaxIdentifierLength", 128); - SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + SqlServerModelBuilderExtensions.UseHiLo(modelBuilder, "EntityFrameworkHiLoSequence"); + + modelBuilder.HasSequence("EntityFrameworkHiLoSequence") + .IncrementsBy(10); modelBuilder.Entity("HomeWork22.Datas.Entities.CostumerEntity", b => { @@ -27,7 +30,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) .ValueGeneratedOnAdd() .HasColumnType("int"); - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + SqlServerPropertyBuilderExtensions.UseHiLo(b.Property("Id")); b.Property("FirstName") .HasMaxLength(50) @@ -49,7 +52,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) .ValueGeneratedOnAdd() .HasColumnType("int"); - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + SqlServerPropertyBuilderExtensions.UseHiLo(b.Property("Id")); b.Property("CostumerId") .HasColumnType("int"); @@ -67,7 +70,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) .ValueGeneratedOnAdd() .HasColumnType("int"); - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + SqlServerPropertyBuilderExtensions.UseHiLo(b.Property("Id")); b.Property("Count") .HasColumnType("int"); @@ -93,7 +96,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) .ValueGeneratedOnAdd() .HasColumnType("int"); - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + SqlServerPropertyBuilderExtensions.UseHiLo(b.Property("Id")); b.Property("Name") .IsRequired() diff --git a/HomeWork22/HomeWork22/Program.cs b/HomeWork22/HomeWork22/Program.cs index d0b5163..1e81a3b 100644 --- a/HomeWork22/HomeWork22/Program.cs +++ b/HomeWork22/HomeWork22/Program.cs @@ -1,4 +1,6 @@ using HomeWork22.Datas; +using HomeWork22.DbWrappers; +using HomeWork22.DbWrappers.Abstracts; using HomeWork22.Repositories; using HomeWork22.Repositories.Abstractions; using HomeWork22.Services; @@ -21,10 +23,10 @@ void ConfigureService(ServiceCollection serviceCollection, IConfiguration config .AddDbContextFactory(option => option .UseSqlServer(connectionString)); - // serviceColection.addwraper - + serviceCollection .AddLogging(login => login.AddConsole()) + .AddScoped, DbContextWrapper>() .AddTransient() .AddTransient() .AddTransient() diff --git a/HomeWork22/HomeWork22/Repositories/Abstractions/ICostumerRepository.cs b/HomeWork22/HomeWork22/Repositories/Abstractions/ICostumerRepository.cs index 6b5beb0..759f2aa 100644 --- a/HomeWork22/HomeWork22/Repositories/Abstractions/ICostumerRepository.cs +++ b/HomeWork22/HomeWork22/Repositories/Abstractions/ICostumerRepository.cs @@ -4,7 +4,12 @@ namespace HomeWork22.Repositories.Abstractions { internal interface ICostumerRepository { - public Task AddCostumer(string lastname, string firstname); - public Task GetCostumer(int id); + public Task AddCostumerAsync(string lastname, string firstname); + public Task GetCostumerAsync(int id); + public Task UpdateCostumerAsync( + int id, + string lastname = null!, + string firstname = null!); + public Task DeleteCostumerAsync(int id); } } diff --git a/HomeWork22/HomeWork22/Repositories/Abstractions/IOrderRepository.cs b/HomeWork22/HomeWork22/Repositories/Abstractions/IOrderRepository.cs index 082a4bd..cbcab39 100644 --- a/HomeWork22/HomeWork22/Repositories/Abstractions/IOrderRepository.cs +++ b/HomeWork22/HomeWork22/Repositories/Abstractions/IOrderRepository.cs @@ -8,5 +8,7 @@ internal interface IOrderRepository public Task AddOrderAsync(int id, List orderItemList); public Task GetOrder(int id); public Task?> GetOrderByCostumerId(int id); + public Task UpDataOrderAsync(int id, List orderItem); + public Task DeleteOrderAsync(int id); } } diff --git a/HomeWork22/HomeWork22/Repositories/Abstractions/IProductRepository.cs b/HomeWork22/HomeWork22/Repositories/Abstractions/IProductRepository.cs index a4c1f13..28834a1 100644 --- a/HomeWork22/HomeWork22/Repositories/Abstractions/IProductRepository.cs +++ b/HomeWork22/HomeWork22/Repositories/Abstractions/IProductRepository.cs @@ -1,10 +1,18 @@ using HomeWork22.Datas.Entities; +using HomeWork22.Dtos; namespace HomeWork22.Repositories.Abstractions { internal interface IProductRepository { - public Task AddProduct(string name, double price); - public Task GetProduct(int id); + public Task AddProductAsync(string name, double price); + public Task GetProductAsync(int id); + public Task DeleteProductAsync(int id); + public Task UpdataProductAsync( + int id, + string name = null!, + double price = 0); + + public Task> GetProductListAsync(RequestPage request); } } diff --git a/HomeWork22/HomeWork22/Repositories/CostumerRepository.cs b/HomeWork22/HomeWork22/Repositories/CostumerRepository.cs index dbc6fd5..eaabbc8 100644 --- a/HomeWork22/HomeWork22/Repositories/CostumerRepository.cs +++ b/HomeWork22/HomeWork22/Repositories/CostumerRepository.cs @@ -1,5 +1,7 @@ using HomeWork22.Datas; using HomeWork22.Datas.Entities; +using HomeWork22.DbWrappers.Abstracts; +using HomeWork22.Models; using HomeWork22.Repositories.Abstractions; using Microsoft.EntityFrameworkCore; @@ -9,12 +11,12 @@ internal class CostumerRepository : ICostumerRepository { private readonly ApplicatDbContext _dbContext; - public CostumerRepository(ApplicatDbContext dbContext) + public CostumerRepository(IDbContextWrapper dbContextWrapper) { - _dbContext = dbContext; + _dbContext = dbContextWrapper.DbContext; } - public async Task AddCostumer(string lastname, string firstname) + public async Task AddCostumerAsync(string lastname, string firstname) { var costumer = new CostumerEntity() { @@ -23,19 +25,37 @@ public async Task AddCostumer(string lastname, string firstname) }; var costm = await _dbContext.AddAsync(costumer); + await _dbContext.SaveChangesAsync(); return costm.Entity.Id; } - //public async Task UpdateCostumers() - //{ - - //} + public async Task UpdateCostumerAsync(int id, string lastname = null!, string firstname = null!) + { + var costumer = await GetCostumerAsync(id); + + costumer.LastName = lastname is null ? costumer.LastName : lastname; + + costumer.FirstName = firstname is null ? costumer.FirstName : firstname; + + await _dbContext.SaveChangesAsync(); + + return costumer; + } + + public async Task DeleteCostumerAsync(int id) + { + var costumer = await GetCostumerAsync(id); + + _dbContext.Costumers.Remove(costumer); + + await _dbContext.SaveChangesAsync(); + } - public async Task GetCostumer(int id) + public async Task GetCostumerAsync(int id) { - return await _dbContext.Costumers.FirstOrDefaultAsync(c=>c.Id == id); + return await _dbContext.Costumers.FirstOrDefaultAsync(c => c.Id == id); } } } diff --git a/HomeWork22/HomeWork22/Repositories/OrderRepository.cs b/HomeWork22/HomeWork22/Repositories/OrderRepository.cs index dfbb2c1..61f911a 100644 --- a/HomeWork22/HomeWork22/Repositories/OrderRepository.cs +++ b/HomeWork22/HomeWork22/Repositories/OrderRepository.cs @@ -1,5 +1,6 @@ using HomeWork22.Datas; using HomeWork22.Datas.Entities; +using HomeWork22.DbWrappers.Abstracts; using HomeWork22.Models; using HomeWork22.Repositories.Abstractions; using Microsoft.EntityFrameworkCore; @@ -10,19 +11,18 @@ internal class OrderRepository : IOrderRepository { private readonly ApplicatDbContext _dbContext; - public OrderRepository(ApplicatDbContext dbContext) + public OrderRepository(IDbContextWrapper dbContextWrapper) { - _dbContext = dbContext; + _dbContext = dbContextWrapper.DbContext; } public async Task AddOrderAsync(int id, List orderItemList) { - var order = await _dbContext - .Orders + var order = await _dbContext.Orders .AddAsync(new OrderEntity() - { - CostumerId = id, - }); + { + CostumerId = id, + }); await _dbContext .OrderItems @@ -32,26 +32,43 @@ await _dbContext Count = s.Count, OrderId = order.Entity.Id, ProductId = s.ProductId, - } - )); + })); await _dbContext.SaveChangesAsync(); return order.Entity.Id; } + public async Task UpDataOrderAsync(int id, List orderItem) + { + var orderUp = await GetOrder(id); + + orderUp.OrderItems = orderItem; + + await _dbContext.SaveChangesAsync(); + + return id; + } + + public async Task DeleteOrderAsync(int id) + { + var order = await GetOrder(id); + + _dbContext.Orders.Remove(order); + + await _dbContext.SaveChangesAsync(); + } + public async Task GetOrder(int id) { - return await _dbContext - .Orders + return await _dbContext.Orders .Include(i => i.OrderItems) .FirstOrDefaultAsync(x=>x.Id == id); } public async Task?> GetOrderByCostumerId(int id) { - return await _dbContext - .Orders + return await _dbContext.Orders .Include(x=>x.OrderItems) .Where(x=>x.CostumerId==id) .ToListAsync(); diff --git a/HomeWork22/HomeWork22/Repositories/ProductRepository.cs b/HomeWork22/HomeWork22/Repositories/ProductRepository.cs index 3e5c4f4..b83be4b 100644 --- a/HomeWork22/HomeWork22/Repositories/ProductRepository.cs +++ b/HomeWork22/HomeWork22/Repositories/ProductRepository.cs @@ -1,5 +1,7 @@ using HomeWork22.Datas; using HomeWork22.Datas.Entities; +using HomeWork22.DbWrappers.Abstracts; +using HomeWork22.Dtos; using HomeWork22.Repositories.Abstractions; using Microsoft.EntityFrameworkCore; @@ -9,12 +11,12 @@ internal class ProductRepository : IProductRepository { private readonly ApplicatDbContext _dbContext; - public ProductRepository(ApplicatDbContext dbContext) + public ProductRepository(IDbContextWrapper dbContextWrapper) { - _dbContext = dbContext; + _dbContext = dbContextWrapper.DbContext; } - public async Task AddProduct(string name, double price) + public async Task AddProductAsync(string name, double price) { var product = new ProductEntity() { @@ -28,9 +30,41 @@ public async Task AddProduct(string name, double price) return products.Entity.Id; } - public async Task GetProduct(int id) + public async Task UpdataProductAsync(int id, string name, double price) { - return await _dbContext.Products.FirstOrDefaultAsync(consumers => consumers.Id == id); + var product = await GetProductAsync(id); + + product!.Price = price == 0 ? product.Price : price; + product.Name = name is null ? product.Name : name; + + await _dbContext.SaveChangesAsync(); + + return product; + } + + public async Task DeleteProductAsync(int id) + { + var product = await GetProductAsync(id); + + _dbContext.Products.Remove(product!); + _dbContext.SaveChanges(); + } + + public async Task GetProductAsync(int id) + { + return await _dbContext.Products + .FirstOrDefaultAsync(product => product.Id == id); + } + + public async Task> GetProductListAsync(RequestPage request) + { + return await _dbContext.Products + .Where(x => x.Price >= request.PriceMin && x.Price <= request.PriceMax) + .Where(x => x.Name == request.Name) + .Skip(request.PageSize * (request.PageNamber - 1)) + .Take(request.PageSize) + .OrderDescending() + .ToListAsync(); } } } diff --git a/HomeWork22/HomeWork22/Services/Abstracts/BaseDataService.cs b/HomeWork22/HomeWork22/Services/Abstracts/BaseDataService.cs new file mode 100644 index 0000000..b0a5994 --- /dev/null +++ b/HomeWork22/HomeWork22/Services/Abstracts/BaseDataService.cs @@ -0,0 +1,67 @@ +using HomeWork22.DbWrappers.Abstracts; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace HomeWork22.Services.Abstracts +{ + internal abstract class BaseDataService : IBaseDataService + where T : DbContext + { + private readonly IDbContextWrapper _dbContextWrapper; + private readonly ILogger _logger; + + public BaseDataService( + IDbContextWrapper dbContextWrapper, + ILogger logger) + { + _dbContextWrapper = dbContextWrapper; + _logger = logger; + } + + protected Task ExecuteSafeAsync(Func action, CancellationToken cancellationToken = default) => ExecuteSafeAsync(token => action(), cancellationToken); + + protected Task ExecuteSafeAsync(Func> action, CancellationToken cancellationToken = default) => ExecuteSafeAsync(token => action(), cancellationToken); + + private async Task ExecuteSafeAsync(Func action, CancellationToken cancellationToken = default) + { + await using var transaction = await _dbContextWrapper.BeginTrasactionAsync(cancellationToken); + + try + { + await action(cancellationToken); + + await transaction.CommitAsync(cancellationToken); + } + catch (Exception ex) + { + await transaction.RollbackAsync(cancellationToken); + + _logger.LogError(ex, $"transaction is roll back, some error"); + + throw; + } + } + + private async Task ExecuteSafeAsync(Func> action, CancellationToken cancellationToken = default) + { + await using var transaction = await _dbContextWrapper.BeginTrasactionAsync(cancellationToken); + + try + { + var result = await action(cancellationToken); + + await transaction.CommitAsync(cancellationToken); + + return result; + } + catch (Exception ex) + { + await transaction.RollbackAsync(cancellationToken); + + _logger.LogError(ex, $"Failed to execute, transaction is rollback"); + + throw; + } + } + } +} diff --git a/HomeWork22/HomeWork22/Services/Abstracts/IBaseDataService.cs b/HomeWork22/HomeWork22/Services/Abstracts/IBaseDataService.cs new file mode 100644 index 0000000..9a0fdc2 --- /dev/null +++ b/HomeWork22/HomeWork22/Services/Abstracts/IBaseDataService.cs @@ -0,0 +1,6 @@ +namespace HomeWork22.Services.Abstracts +{ + internal interface IBaseDataService + { + } +} diff --git a/HomeWork22/HomeWork22/Services/Abstracts/ICostumerService.cs b/HomeWork22/HomeWork22/Services/Abstracts/ICostumerService.cs index 9c94961..e53254c 100644 --- a/HomeWork22/HomeWork22/Services/Abstracts/ICostumerService.cs +++ b/HomeWork22/HomeWork22/Services/Abstracts/ICostumerService.cs @@ -6,5 +6,10 @@ internal interface ICostumerService { public Task AddCostumerAsync(string lastname, string firstname); public Task GetCostumerAsync(int id); + public Task UpdateCostumerAsync( + int id, + string lastname = null!, + string firstname = null!); + public Task DeleteCostumerAsync(int id); } } diff --git a/HomeWork22/HomeWork22/Services/Abstracts/IOrderService.cs b/HomeWork22/HomeWork22/Services/Abstracts/IOrderService.cs index 799c9f1..f7720fa 100644 --- a/HomeWork22/HomeWork22/Services/Abstracts/IOrderService.cs +++ b/HomeWork22/HomeWork22/Services/Abstracts/IOrderService.cs @@ -7,5 +7,7 @@ internal interface IOrderService public Task AddOrderAsync(int costumerId, List orderItems); public Task GetOrderAsync(int id); public Task> GetOrderByCostumerId(int id); + public Task DeleteOrderAsync(int id); + public Task UpdateOrderAsync(int id, List items); } } diff --git a/HomeWork22/HomeWork22/Services/Abstracts/IProductService.cs b/HomeWork22/HomeWork22/Services/Abstracts/IProductService.cs index 5d83389..3d964b1 100644 --- a/HomeWork22/HomeWork22/Services/Abstracts/IProductService.cs +++ b/HomeWork22/HomeWork22/Services/Abstracts/IProductService.cs @@ -1,4 +1,5 @@ -using HomeWork22.Models; +using HomeWork22.Dtos; +using HomeWork22.Models; namespace HomeWork22.Services.Abstracts { @@ -6,5 +7,8 @@ internal interface IProductService { public Task AddProductAsync(string name, double price); public Task GetProductAsync(int id); + public Task UpdataProductAsync(int id, string name = null!, double price = 0); + public Task DeleteProduct(int id); + public Task> GetViewProductListAsync(RequestPage request); } } diff --git a/HomeWork22/HomeWork22/Services/CostumerService.cs b/HomeWork22/HomeWork22/Services/CostumerService.cs index f079b55..8fc223b 100644 --- a/HomeWork22/HomeWork22/Services/CostumerService.cs +++ b/HomeWork22/HomeWork22/Services/CostumerService.cs @@ -1,37 +1,67 @@ -using HomeWork22.Models; +using HomeWork22.Datas; +using HomeWork22.DbWrappers.Abstracts; +using HomeWork22.Models; using HomeWork22.Repositories.Abstractions; using HomeWork22.Services.Abstracts; using Microsoft.Extensions.Logging; namespace HomeWork22.Services { - internal class CostumerService : ICostumerService + internal class CostumerService : BaseDataService, ICostumerService { private readonly ICostumerRepository _costumerRepository; private readonly ILogger _logger; - public CostumerService(ICostumerRepository costumerRepository, ILogger logger) - { + public CostumerService( + ICostumerRepository costumerRepository, + ILogger loggerService, + IDbContextWrapper dbContextWrapper, + ILogger> logger) + : base + (dbContextWrapper, logger) + { _costumerRepository = costumerRepository; - _logger = logger; + _logger = loggerService; } public async Task AddCostumerAsync(string lastname, string firstname) { - var id = await _costumerRepository.AddCostumer(lastname, firstname); + return await ExecuteSafeAsync(async () => + { + var id = await _costumerRepository.AddCostumerAsync(lastname, firstname); + + _logger.LogInformation($"Succesfull create costumer with id: {id}"); + + return id; + }); + } + + public async Task UpdateCostumerAsync(int id, string lastname = null!, string firstname = null!) + { + var costumers = await _costumerRepository.UpdateCostumerAsync(id, lastname); - _logger.LogInformation($"Succesfull create costumer with id: {id}"); - - return id; + return new Costumer() + { + Id = costumers.Id, + Lastname = costumers.LastName, + Firstname = costumers.FirstName, + Fullname = $"{costumers.LastName} {costumers.FirstName}" + }; + } + + public async Task DeleteCostumerAsync(int id) + { + await _costumerRepository.DeleteCostumerAsync(id); } public async Task GetCostumerAsync(int id) { - var costumerEntity = await _costumerRepository.GetCostumer(id); + var costumerEntity = await _costumerRepository.GetCostumerAsync(id); if (costumerEntity is null) { _logger.LogWarning($"Costumer is not founded with id: {id}"); + return null!; } @@ -40,7 +70,7 @@ public async Task GetCostumerAsync(int id) Id = costumerEntity.Id, Firstname = costumerEntity.FirstName, Lastname = costumerEntity.LastName, - Fullname = $"{costumerEntity.FirstName} {costumerEntity.LastName}", + Fullname = $"{costumerEntity.LastName} {costumerEntity.FirstName} ", }; } } diff --git a/HomeWork22/HomeWork22/Services/OrderService.cs b/HomeWork22/HomeWork22/Services/OrderService.cs index 241103e..d29dd74 100644 --- a/HomeWork22/HomeWork22/Services/OrderService.cs +++ b/HomeWork22/HomeWork22/Services/OrderService.cs @@ -1,19 +1,28 @@ -using HomeWork22.Models; +using HomeWork22.Datas; +using HomeWork22.Datas.Entities; +using HomeWork22.DbWrappers.Abstracts; +using HomeWork22.Models; using HomeWork22.Repositories.Abstractions; using HomeWork22.Services.Abstracts; using Microsoft.Extensions.Logging; namespace HomeWork22.Services { - internal class OrderService : IOrderService + internal class OrderService : BaseDataService, IOrderService { private readonly IOrderRepository _orderRepository; private readonly ILogger _logger; - public OrderService(IOrderRepository orderRepository, ILogger logger) + public OrderService( + IOrderRepository orderRepository, + ILogger loggerService, + ILogger> logger, + IDbContextWrapper dbContextWrapper) + : base + (dbContextWrapper, logger) { _orderRepository = orderRepository; - _logger = logger; + _logger = loggerService; } public async Task AddOrderAsync(int costumerId, List orderItems) @@ -23,6 +32,7 @@ public async Task AddOrderAsync(int costumerId, List orderItems) _logger.LogInformation($"Order seccusfull created with id {id}"); return id; + } public async Task GetOrderAsync(int id) @@ -32,6 +42,7 @@ public async Task GetOrderAsync(int id) if (order is null) { _logger.LogWarning($"Order don`t finded with id {id}"); + return null!; } @@ -54,6 +65,33 @@ public async Task GetOrderAsync(int id) }; } + public async Task DeleteOrderAsync(int id) + { + await _orderRepository.DeleteOrderAsync(id); + _logger.LogInformation($"Order {id} is seccusfull delete"); + } + + public async Task UpdateOrderAsync(int id, List items) + { + var entity = items.Select(s => new OrderItemEntity() + { + Count = s.Count, + ProductId = s.ProductId, + Product = new ProductEntity() + { + Id = s.Product.Id, + Name = s.Product.Name, + Price = s.Product.Price, + } + }).ToList(); + + var idOrder = await _orderRepository.UpDataOrderAsync(id, entity); + + _logger.LogInformation($"Update succesfull {idOrder}"); + + return idOrder; + } + public async Task> GetOrderByCostumerId(int id) { var order = await _orderRepository.GetOrderByCostumerId(id); @@ -65,7 +103,7 @@ public async Task> GetOrderByCostumerId(int id) return null!; } - return order.Select(s => new Order() + return order.Select(s => new Order() { Id = s.Id, OrderItem = s.OrderItems.Select(r => new OrderItem() @@ -73,7 +111,7 @@ public async Task> GetOrderByCostumerId(int id) Count = r.Count, ProductId = r.ProductId, Product = new Product() - { + { Id = r.Product.Id, Name = r.Product.Name, Price = r.Product.Price, diff --git a/HomeWork22/HomeWork22/Services/ProductService.cs b/HomeWork22/HomeWork22/Services/ProductService.cs index 2fc3633..4eaccec 100644 --- a/HomeWork22/HomeWork22/Services/ProductService.cs +++ b/HomeWork22/HomeWork22/Services/ProductService.cs @@ -1,36 +1,49 @@ -using HomeWork22.Models; +using HomeWork22.Datas; +using HomeWork22.DbWrappers.Abstracts; +using HomeWork22.Dtos; +using HomeWork22.Models; using HomeWork22.Repositories.Abstractions; using HomeWork22.Services.Abstracts; using Microsoft.Extensions.Logging; namespace HomeWork22.Services { - internal class ProductService : IProductService + internal class ProductService : BaseDataService, IProductService { private readonly IProductRepository _productRepository; private readonly ILogger _logger; - public ProductService(IProductRepository productRepository, ILogger logger) + public ProductService( + IProductRepository productRepository, + ILogger loggerService, + ILogger> logger, + IDbContextWrapper dbContextWrapper) + : base + (dbContextWrapper, logger) { _productRepository = productRepository; - _logger = logger; + _logger = loggerService; } public async Task AddProductAsync(string name, double price) { - var id = await _productRepository.AddProduct(name, price); + return await ExecuteSafeAsync(async () => + { + var id = await _productRepository.AddProductAsync(name, price); - _logger.LogInformation($"Product succesfull create with id: {id}"); + _logger.LogInformation($"Product succesfull create with id: {id}"); - return id; + return id; + }); } public async Task GetProductAsync(int id) { - var product = await _productRepository.GetProduct(id); + var product = await _productRepository.GetProductAsync(id); if (product is null) { _logger.LogWarning("Product with this id don`t exist"); + return null!; } @@ -41,5 +54,34 @@ public async Task GetProductAsync(int id) Price = product.Price, }; } + + public async Task DeleteProduct(int id) + { + await _productRepository.DeleteProductAsync(id); + + _logger.LogInformation($"Product seccesfull deleted: {id}"); + } + + public async Task UpdataProductAsync(int id, string name = null!, double price = 0) + { + await _productRepository.UpdataProductAsync(id, name, price); + + _logger.LogInformation($"Product with id: {id} seccusfull update"); + + return id; + } + + public async Task> GetViewProductListAsync(RequestPage request) + { + var product = await _productRepository.GetProductListAsync(request); + + return product.Select(x => new Product() + { + Id = x.Id, + Name = x.Name, + Price = x.Price, + + }).ToList(); + } } } diff --git a/HomeWork22/HomeWork22/Wrappers/Abstracts/IDbContextWrapper.cs b/HomeWork22/HomeWork22/Wrappers/Abstracts/IDbContextWrapper.cs new file mode 100644 index 0000000..9220d92 --- /dev/null +++ b/HomeWork22/HomeWork22/Wrappers/Abstracts/IDbContextWrapper.cs @@ -0,0 +1,12 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; + +namespace HomeWork22.DbWrappers.Abstracts +{ + internal interface IDbContextWrapper where T : DbContext + { + public T DbContext { get; } + + public Task BeginTrasactionAsync(CancellationToken cancellationToken); + } +} diff --git a/HomeWork22/HomeWork22/Wrappers/DbContextWrapper.cs b/HomeWork22/HomeWork22/Wrappers/DbContextWrapper.cs new file mode 100644 index 0000000..91faa47 --- /dev/null +++ b/HomeWork22/HomeWork22/Wrappers/DbContextWrapper.cs @@ -0,0 +1,24 @@ +using HomeWork22.DbWrappers.Abstracts; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; + +namespace HomeWork22.DbWrappers +{ + internal class DbContextWrapper : IDbContextWrapper + where T : DbContext + { + private readonly T _dbContext; + + public DbContextWrapper(IDbContextFactory dbContextFactory) + { + _dbContext = dbContextFactory.CreateDbContext(); + } + + public T DbContext => _dbContext; + + public Task BeginTrasactionAsync(CancellationToken cancellationToken) + { + return _dbContext.Database.BeginTransactionAsync(cancellationToken); + } + } +} From 5c259103d0d4b54afa9da4f58d3969ea69a80e9e Mon Sep 17 00:00:00 2001 From: BabychMaksym Date: Thu, 4 Apr 2024 21:17:29 +0300 Subject: [PATCH 3/4] change HomeWork 22 --- HomeWork22/HomeWork22/App.cs | 4 +- HomeWork22/HomeWork22/Dtos/RequestPage.cs | 4 +- .../Abstractions/ICostumerRepository.cs | 2 +- .../Abstractions/IOrderRepository.cs | 4 +- .../Abstractions/IProductRepository.cs | 2 +- .../Repositories/CostumerRepository.cs | 15 +- .../Repositories/OrderRepository.cs | 16 +- .../Repositories/ProductRepository.cs | 21 ++- .../Services/Abstracts/ICostumerService.cs | 2 +- .../Services/Abstracts/IOrderService.cs | 4 +- .../Services/Abstracts/IProductService.cs | 4 +- .../HomeWork22/Services/CostumerService.cs | 28 +-- .../HomeWork22/Services/OrderService.cs | 160 +++++++++++------- .../HomeWork22/Services/ProductService.cs | 75 +++++--- 14 files changed, 224 insertions(+), 117 deletions(-) diff --git a/HomeWork22/HomeWork22/App.cs b/HomeWork22/HomeWork22/App.cs index 0ce1765..491f313 100644 --- a/HomeWork22/HomeWork22/App.cs +++ b/HomeWork22/HomeWork22/App.cs @@ -27,7 +27,7 @@ public async Task StartAsync() var idOrange = await _productService.AddProductAsync("Orange", 10.50); - await _productService.UpdataProductAsync(idLimon, price: 11); + await _productService.UpdataProductAsync(idOrange, name: "Limon", price: 11); var productLimon = await _productService.GetProductAsync(idLimon); @@ -55,7 +55,7 @@ public async Task StartAsync() var request = new RequestPage() { - Name = "", + Name = "Limon", PageNamber = 1, PageSize = 20, PriceMax = 10, diff --git a/HomeWork22/HomeWork22/Dtos/RequestPage.cs b/HomeWork22/HomeWork22/Dtos/RequestPage.cs index 3b6dbdc..de9e80f 100644 --- a/HomeWork22/HomeWork22/Dtos/RequestPage.cs +++ b/HomeWork22/HomeWork22/Dtos/RequestPage.cs @@ -1,6 +1,4 @@ -using Microsoft.Identity.Client; - -namespace HomeWork22.Dtos +namespace HomeWork22.Dtos { internal class RequestPage : PageDto { diff --git a/HomeWork22/HomeWork22/Repositories/Abstractions/ICostumerRepository.cs b/HomeWork22/HomeWork22/Repositories/Abstractions/ICostumerRepository.cs index 759f2aa..baeab6c 100644 --- a/HomeWork22/HomeWork22/Repositories/Abstractions/ICostumerRepository.cs +++ b/HomeWork22/HomeWork22/Repositories/Abstractions/ICostumerRepository.cs @@ -10,6 +10,6 @@ public Task UpdateCostumerAsync( int id, string lastname = null!, string firstname = null!); - public Task DeleteCostumerAsync(int id); + public Task DeleteCostumerAsync(int id); } } diff --git a/HomeWork22/HomeWork22/Repositories/Abstractions/IOrderRepository.cs b/HomeWork22/HomeWork22/Repositories/Abstractions/IOrderRepository.cs index cbcab39..d039779 100644 --- a/HomeWork22/HomeWork22/Repositories/Abstractions/IOrderRepository.cs +++ b/HomeWork22/HomeWork22/Repositories/Abstractions/IOrderRepository.cs @@ -8,7 +8,7 @@ internal interface IOrderRepository public Task AddOrderAsync(int id, List orderItemList); public Task GetOrder(int id); public Task?> GetOrderByCostumerId(int id); - public Task UpDataOrderAsync(int id, List orderItem); - public Task DeleteOrderAsync(int id); + public Task UpDataOrderAsync(int id, List orderItem); + public Task DeleteOrderAsync(int id); } } diff --git a/HomeWork22/HomeWork22/Repositories/Abstractions/IProductRepository.cs b/HomeWork22/HomeWork22/Repositories/Abstractions/IProductRepository.cs index 28834a1..156ce29 100644 --- a/HomeWork22/HomeWork22/Repositories/Abstractions/IProductRepository.cs +++ b/HomeWork22/HomeWork22/Repositories/Abstractions/IProductRepository.cs @@ -7,7 +7,7 @@ internal interface IProductRepository { public Task AddProductAsync(string name, double price); public Task GetProductAsync(int id); - public Task DeleteProductAsync(int id); + public Task DeleteProductAsync(int id); public Task UpdataProductAsync( int id, string name = null!, diff --git a/HomeWork22/HomeWork22/Repositories/CostumerRepository.cs b/HomeWork22/HomeWork22/Repositories/CostumerRepository.cs index eaabbc8..3cb625c 100644 --- a/HomeWork22/HomeWork22/Repositories/CostumerRepository.cs +++ b/HomeWork22/HomeWork22/Repositories/CostumerRepository.cs @@ -35,6 +35,11 @@ public async Task UpdateCostumerAsync(int id, string lastname = { var costumer = await GetCostumerAsync(id); + if (costumer is null) + { + return null; + } + costumer.LastName = lastname is null ? costumer.LastName : lastname; costumer.FirstName = firstname is null ? costumer.FirstName : firstname; @@ -44,13 +49,19 @@ public async Task UpdateCostumerAsync(int id, string lastname = return costumer; } - public async Task DeleteCostumerAsync(int id) + public async Task DeleteCostumerAsync(int id) { var costumer = await GetCostumerAsync(id); - _dbContext.Costumers.Remove(costumer); + if(costumer is null) + { + return null; + } + var status = _dbContext.Costumers.Remove(costumer); await _dbContext.SaveChangesAsync(); + + return status.ToString(); } public async Task GetCostumerAsync(int id) diff --git a/HomeWork22/HomeWork22/Repositories/OrderRepository.cs b/HomeWork22/HomeWork22/Repositories/OrderRepository.cs index 61f911a..0a00a94 100644 --- a/HomeWork22/HomeWork22/Repositories/OrderRepository.cs +++ b/HomeWork22/HomeWork22/Repositories/OrderRepository.cs @@ -39,24 +39,30 @@ await _dbContext return order.Entity.Id; } - public async Task UpDataOrderAsync(int id, List orderItem) + public async Task UpDataOrderAsync(int id, List orderItem) { var orderUp = await GetOrder(id); - + orderUp.OrderItems = orderItem; await _dbContext.SaveChangesAsync(); - return id; + return orderUp; } - public async Task DeleteOrderAsync(int id) + public async Task DeleteOrderAsync(int id) { var order = await GetOrder(id); - _dbContext.Orders.Remove(order); + if (order is null) + { + return null; + } + + var status = _dbContext.Orders.Remove(order); await _dbContext.SaveChangesAsync(); + return status.ToString(); } public async Task GetOrder(int id) diff --git a/HomeWork22/HomeWork22/Repositories/ProductRepository.cs b/HomeWork22/HomeWork22/Repositories/ProductRepository.cs index b83be4b..4e04cfc 100644 --- a/HomeWork22/HomeWork22/Repositories/ProductRepository.cs +++ b/HomeWork22/HomeWork22/Repositories/ProductRepository.cs @@ -15,7 +15,6 @@ public ProductRepository(IDbContextWrapper dbContextWrapper) { _dbContext = dbContextWrapper.DbContext; } - public async Task AddProductAsync(string name, double price) { var product = new ProductEntity() @@ -42,12 +41,17 @@ public async Task UpdataProductAsync(int id, string name, double return product; } - public async Task DeleteProductAsync(int id) + public async Task DeleteProductAsync(int id) { var product = await GetProductAsync(id); - - _dbContext.Products.Remove(product!); + if (product is null) + { + return null!; + } + var status = _dbContext.Products.Remove(product!); _dbContext.SaveChanges(); + + return status.ToString(); } public async Task GetProductAsync(int id) @@ -58,13 +62,12 @@ public async Task DeleteProductAsync(int id) public async Task> GetProductListAsync(RequestPage request) { - return await _dbContext.Products - .Where(x => x.Price >= request.PriceMin && x.Price <= request.PriceMax) - .Where(x => x.Name == request.Name) + return _dbContext.Products.AsEnumerable() + .Where(x => x.Price == request.PriceMax || x.Name.Contains(request.Name)) .Skip(request.PageSize * (request.PageNamber - 1)) .Take(request.PageSize) - .OrderDescending() - .ToListAsync(); + .OrderByDescending(x=>x.Name) + .ToList(); } } } diff --git a/HomeWork22/HomeWork22/Services/Abstracts/ICostumerService.cs b/HomeWork22/HomeWork22/Services/Abstracts/ICostumerService.cs index e53254c..5680445 100644 --- a/HomeWork22/HomeWork22/Services/Abstracts/ICostumerService.cs +++ b/HomeWork22/HomeWork22/Services/Abstracts/ICostumerService.cs @@ -10,6 +10,6 @@ public Task UpdateCostumerAsync( int id, string lastname = null!, string firstname = null!); - public Task DeleteCostumerAsync(int id); + public Task DeleteCostumerAsync(int id); } } diff --git a/HomeWork22/HomeWork22/Services/Abstracts/IOrderService.cs b/HomeWork22/HomeWork22/Services/Abstracts/IOrderService.cs index f7720fa..2ac0926 100644 --- a/HomeWork22/HomeWork22/Services/Abstracts/IOrderService.cs +++ b/HomeWork22/HomeWork22/Services/Abstracts/IOrderService.cs @@ -7,7 +7,7 @@ internal interface IOrderService public Task AddOrderAsync(int costumerId, List orderItems); public Task GetOrderAsync(int id); public Task> GetOrderByCostumerId(int id); - public Task DeleteOrderAsync(int id); - public Task UpdateOrderAsync(int id, List items); + public Task DeleteOrderAsync(int id); + public Task UpdateOrderAsync(int id, List items); } } diff --git a/HomeWork22/HomeWork22/Services/Abstracts/IProductService.cs b/HomeWork22/HomeWork22/Services/Abstracts/IProductService.cs index 3d964b1..0f9d586 100644 --- a/HomeWork22/HomeWork22/Services/Abstracts/IProductService.cs +++ b/HomeWork22/HomeWork22/Services/Abstracts/IProductService.cs @@ -7,8 +7,8 @@ internal interface IProductService { public Task AddProductAsync(string name, double price); public Task GetProductAsync(int id); - public Task UpdataProductAsync(int id, string name = null!, double price = 0); - public Task DeleteProduct(int id); + public Task UpdataProductAsync(int id, string name = null!, double price = 0); + public Task DeleteProduct(int id); public Task> GetViewProductListAsync(RequestPage request); } } diff --git a/HomeWork22/HomeWork22/Services/CostumerService.cs b/HomeWork22/HomeWork22/Services/CostumerService.cs index 8fc223b..5503e00 100644 --- a/HomeWork22/HomeWork22/Services/CostumerService.cs +++ b/HomeWork22/HomeWork22/Services/CostumerService.cs @@ -38,20 +38,28 @@ public async Task AddCostumerAsync(string lastname, string firstname) public async Task UpdateCostumerAsync(int id, string lastname = null!, string firstname = null!) { - var costumers = await _costumerRepository.UpdateCostumerAsync(id, lastname); - - return new Costumer() + return await ExecuteSafeAsync(async () => { - Id = costumers.Id, - Lastname = costumers.LastName, - Firstname = costumers.FirstName, - Fullname = $"{costumers.LastName} {costumers.FirstName}" - }; + var costumers = await _costumerRepository.UpdateCostumerAsync(id, lastname); + + return new Costumer() + { + Id = costumers.Id, + Lastname = costumers.LastName, + Firstname = costumers.FirstName, + Fullname = $"{costumers.LastName} {costumers.FirstName}" + }; + }); } - public async Task DeleteCostumerAsync(int id) + public async Task DeleteCostumerAsync(int id) { - await _costumerRepository.DeleteCostumerAsync(id); + return await ExecuteSafeAsync(async () => + { + var status = await _costumerRepository.DeleteCostumerAsync(id); + + return status; + }); } public async Task GetCostumerAsync(int id) diff --git a/HomeWork22/HomeWork22/Services/OrderService.cs b/HomeWork22/HomeWork22/Services/OrderService.cs index d29dd74..6e70a2d 100644 --- a/HomeWork22/HomeWork22/Services/OrderService.cs +++ b/HomeWork22/HomeWork22/Services/OrderService.cs @@ -27,97 +27,143 @@ public OrderService( public async Task AddOrderAsync(int costumerId, List orderItems) { - var id = await _orderRepository.AddOrderAsync(costumerId, orderItems); + return await ExecuteSafeAsync(async () => + { + var id = await _orderRepository.AddOrderAsync(costumerId, orderItems); - _logger.LogInformation($"Order seccusfull created with id {id}"); + _logger.LogInformation($"Order seccusfull created with id {id}"); - return id; + return id; + }); } public async Task GetOrderAsync(int id) { - var order = await _orderRepository.GetOrder(id); - - if (order is null) + return await ExecuteSafeAsync(async() => { - _logger.LogWarning($"Order don`t finded with id {id}"); + var order = await _orderRepository.GetOrder(id); - return null!; - } + if (order is null) + { + _logger.LogWarning($"Order don`t finded with id {id}"); - return new Order() - { - Id = order.Id, + return null!; + } - OrderItem = order.OrderItems.Select(s => new OrderItem() + return new Order() { - Count = s.Count, - ProductId = s.ProductId, + Id = order.Id, - Product = new Product() + OrderItem = order.OrderItems.Select(s => new OrderItem() { - Id = s.Product.Id, - Name = s.Product.Name, - Price = s.Product.Price, - } - }) - }; + Count = s.Count, + ProductId = s.ProductId, + + Product = new Product() + { + Id = s.Product.Id, + Name = s.Product.Name, + Price = s.Product.Price, + } + }) + }; + }); } - public async Task DeleteOrderAsync(int id) + public async Task DeleteOrderAsync(int id) { - await _orderRepository.DeleteOrderAsync(id); - _logger.LogInformation($"Order {id} is seccusfull delete"); + return await ExecuteSafeAsync(async () => + { + var status = await _orderRepository.DeleteOrderAsync(id); + + if (status is null) + { + _logger.LogWarning($"Order don`t finded with id {id}"); + + return null!; + } + + _logger.LogInformation($"Order {id} is seccusfull delete"); + return status; + }); } - public async Task UpdateOrderAsync(int id, List items) + public async Task UpdateOrderAsync(int id, List items) { - var entity = items.Select(s => new OrderItemEntity() + return await ExecuteSafeAsync(async () => { - Count = s.Count, - ProductId = s.ProductId, - Product = new ProductEntity() + var entity = items.Select(s => new OrderItemEntity() { - Id = s.Product.Id, - Name = s.Product.Name, - Price = s.Product.Price, - } - }).ToList(); + Count = s.Count, + ProductId = s.ProductId, + Product = new ProductEntity() + { + Id = s.Product.Id, + Name = s.Product.Name, + Price = s.Product.Price, + } + }).ToList(); + + var order = await _orderRepository.UpDataOrderAsync(id, entity); + if (order is null) + { + _logger.LogWarning($"Order don`t finded with id {id}"); - var idOrder = await _orderRepository.UpDataOrderAsync(id, entity); + return null!; + } - _logger.LogInformation($"Update succesfull {idOrder}"); + _logger.LogInformation($"Update succesfull {order.Id}"); - return idOrder; + return new Order() + { + Id = order.Id, + Costumer = new Costumer() + { + Id = order.Costumer.Id, + Firstname = order.Costumer.FirstName, + Lastname = order.Costumer.LastName, + Fullname = $"{order.Costumer.FirstName} {order.Costumer.LastName}" + }, + OrderItem = new List().Select(s => new OrderItem() + { + Count = s.Count, + Product = s.Product, + ProductId = s.ProductId + }), + }; + }); } public async Task> GetOrderByCostumerId(int id) { - var order = await _orderRepository.GetOrderByCostumerId(id); - - if (order is null) + return await ExecuteSafeAsync(async () => { - _logger.LogWarning($"Order not founded with id {id}"); + var order = await _orderRepository.GetOrderByCostumerId(id); - return null!; - } + if (order is null) + { + _logger.LogWarning($"Order not founded with id {id}"); - return order.Select(s => new Order() - { - Id = s.Id, - OrderItem = s.OrderItems.Select(r => new OrderItem() + return null!; + } + + return order.Select(s => new Order() { - Count = r.Count, - ProductId = r.ProductId, - Product = new Product() + Id = s.Id, + OrderItem = s.OrderItems.Select(r => new OrderItem() { - Id = r.Product.Id, - Name = r.Product.Name, - Price = r.Product.Price, - } - }) - }).ToList(); + Count = r.Count, + ProductId = r.ProductId, + Product = new Product() + { + Id = r.Product.Id, + Name = r.Product.Name, + Price = r.Product.Price, + } + }) + }).ToList(); + }); } } } diff --git a/HomeWork22/HomeWork22/Services/ProductService.cs b/HomeWork22/HomeWork22/Services/ProductService.cs index 4eaccec..d978d05 100644 --- a/HomeWork22/HomeWork22/Services/ProductService.cs +++ b/HomeWork22/HomeWork22/Services/ProductService.cs @@ -21,7 +21,7 @@ public ProductService( (dbContextWrapper, logger) { _productRepository = productRepository; - _logger = loggerService; + _logger = loggerService; } public async Task AddProductAsync(string name, double price) @@ -38,8 +38,47 @@ public async Task AddProductAsync(string name, double price) public async Task GetProductAsync(int id) { - var product = await _productRepository.GetProductAsync(id); + return await ExecuteSafeAsync(async () => + { + var product = await _productRepository.GetProductAsync(id); + + if (product is null) + { + _logger.LogWarning("Product with this id don`t exist"); + + return null!; + } + + return new Product() + { + Id = product.Id, + Name = product.Name, + Price = product.Price, + }; + }); + } + public async Task DeleteProduct(int id) + { + return await ExecuteSafeAsync(async () => + { + var status = await _productRepository.DeleteProductAsync(id); + + if (status is null) + { + _logger.LogWarning($"product don`t finded with id {id}"); + + return null!; + } + _logger.LogInformation($"Product seccesfull deleted: {id}"); + + return status; + }); + } + + public async Task UpdataProductAsync(int id, string name = null!, double price = 0) + { + var product = await _productRepository.UpdataProductAsync(id, name, price); if (product is null) { _logger.LogWarning("Product with this id don`t exist"); @@ -47,6 +86,8 @@ public async Task GetProductAsync(int id) return null!; } + _logger.LogInformation($"Product with id: {id} seccusfull update"); + return new Product() { Id = product.Id, @@ -55,33 +96,27 @@ public async Task GetProductAsync(int id) }; } - public async Task DeleteProduct(int id) - { - await _productRepository.DeleteProductAsync(id); - - _logger.LogInformation($"Product seccesfull deleted: {id}"); - } - - public async Task UpdataProductAsync(int id, string name = null!, double price = 0) + public async Task> GetViewProductListAsync(RequestPage request) { - await _productRepository.UpdataProductAsync(id, name, price); - - _logger.LogInformation($"Product with id: {id} seccusfull update"); + return await ExecuteSafeAsync(async () => + { + var product = await _productRepository.GetProductListAsync(request); - return id; - } + if (product is null) + { + _logger.LogWarning("Product with this id don`t exist"); - public async Task> GetViewProductListAsync(RequestPage request) - { - var product = await _productRepository.GetProductListAsync(request); + return null!; + } - return product.Select(x => new Product() + return product.Select(x => new Product() { Id = x.Id, Name = x.Name, - Price = x.Price, + Price = x.Price, }).ToList(); + }); } } } From 3ce67dd0ffc02ec9384cae916d66e4f685d95bb6 Mon Sep 17 00:00:00 2001 From: BabychMaksym Date: Mon, 8 Apr 2024 19:34:35 +0300 Subject: [PATCH 4/4] -- --- .../Abstractions/IOrderRepository.cs | 2 +- .../Repositories/OrderRepository.cs | 2 +- .../HomeWork22/Services/OrderService.cs | 20 +++++++++++++++++-- 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/HomeWork22/HomeWork22/Repositories/Abstractions/IOrderRepository.cs b/HomeWork22/HomeWork22/Repositories/Abstractions/IOrderRepository.cs index d039779..7c10a63 100644 --- a/HomeWork22/HomeWork22/Repositories/Abstractions/IOrderRepository.cs +++ b/HomeWork22/HomeWork22/Repositories/Abstractions/IOrderRepository.cs @@ -5,7 +5,7 @@ namespace HomeWork22.Repositories.Abstractions { internal interface IOrderRepository { - public Task AddOrderAsync(int id, List orderItemList); + public Task AddOrderAsync(int id, List orderItemList); public Task GetOrder(int id); public Task?> GetOrderByCostumerId(int id); public Task UpDataOrderAsync(int id, List orderItem); diff --git a/HomeWork22/HomeWork22/Repositories/OrderRepository.cs b/HomeWork22/HomeWork22/Repositories/OrderRepository.cs index 0a00a94..ec2beb4 100644 --- a/HomeWork22/HomeWork22/Repositories/OrderRepository.cs +++ b/HomeWork22/HomeWork22/Repositories/OrderRepository.cs @@ -16,7 +16,7 @@ public OrderRepository(IDbContextWrapper dbContextWrapper) _dbContext = dbContextWrapper.DbContext; } - public async Task AddOrderAsync(int id, List orderItemList) + public async Task AddOrderAsync(int id, List orderItemList) { var order = await _dbContext.Orders .AddAsync(new OrderEntity() diff --git a/HomeWork22/HomeWork22/Services/OrderService.cs b/HomeWork22/HomeWork22/Services/OrderService.cs index 6e70a2d..5e14ad5 100644 --- a/HomeWork22/HomeWork22/Services/OrderService.cs +++ b/HomeWork22/HomeWork22/Services/OrderService.cs @@ -29,7 +29,23 @@ public async Task AddOrderAsync(int costumerId, List orderItems) { return await ExecuteSafeAsync(async () => { - var id = await _orderRepository.AddOrderAsync(costumerId, orderItems); + var orderItemEntity = new List(); + + orderItems.ForEach(s => + orderItemEntity.Add(new OrderItemEntity() + { + ProductId = s.ProductId, + Count = s.Count, + Product = new ProductEntity() + { + Id = s.Product.Id, + Price = s.Product.Price, + Name = s.Product.Name, + OrderItems = orderItemEntity + } + })); + + var id = await _orderRepository.AddOrderAsync(costumerId, orderItemEntity); _logger.LogInformation($"Order seccusfull created with id {id}"); @@ -40,7 +56,7 @@ public async Task AddOrderAsync(int costumerId, List orderItems) public async Task GetOrderAsync(int id) { - return await ExecuteSafeAsync(async() => + return await ExecuteSafeAsync(async () => { var order = await _orderRepository.GetOrder(id);