From d5d52daa53abbe83c7c06c0954aaee76cdaece9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A4=D1=80=D0=BE=D0=BB=D0=BE=D0=B2?= Date: Mon, 2 Aug 2021 12:52:44 +0500 Subject: [PATCH] + --- .../Services/CrudService.cs | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 AsbCloudInfrastructure/Services/CrudService.cs diff --git a/AsbCloudInfrastructure/Services/CrudService.cs b/AsbCloudInfrastructure/Services/CrudService.cs new file mode 100644 index 00000000..5ce7a071 --- /dev/null +++ b/AsbCloudInfrastructure/Services/CrudService.cs @@ -0,0 +1,81 @@ +using System.Collections.Generic; +using System.Linq; +using AsbCloudDb.Model; +using AsbCloudApp.Services; +using Mapster; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; + +namespace AsbCloudInfrastructure.Services +{ + public class CrudService + where TModel : class, IId + { + private readonly DbContext context; + private readonly IAsbCloudDbContext db; + private readonly DbSet dbSet; + + public CrudService(IAsbCloudDbContext db) + { + this.db = db; + dbSet = context.Set(); + } + + public IEnumerable GetAll(System.Linq.Expressions.Expression< System.Func> predicate = null) + { + IQueryable entities = dbSet; + + if(predicate is not null) + entities = entities.Where(predicate); + + var dto = entities.Adapt(); + return dto; + } + + public Tdto Get(int id) + { + var entity = dbSet.FirstOrDefault(e => e.Id == id); + + var dto = entity.Adapt(); + return dto; + } + + public Tdto Insert(Tdto newItem) + { + var newEntity = newItem.Adapt(); + var dbEntity = dbSet.Add(newEntity); + db.SaveChanges(); + return dbEntity.Entity.Adapt(); + } + + public IEnumerable InsertRange(IEnumerable newItems) + { + var newEntities = newItems.Adapt< IEnumerable>(); + var dbEntities = new Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry[newItems.Count()]; + + for (int i = 0; i < dbEntities.Length; i++) + dbEntities[i] = dbSet.Add(newEntities.ElementAt(i)); + + db.SaveChanges(); + return dbEntities.Select(e => e.Entity.Adapt()); + } + + public Tdto Update(Tdto item) + { + var newEntity = item.Adapt(); + var dbEntity = dbSet.Update(newEntity); + db.SaveChanges(); + return dbEntity.Entity.Adapt(); + } + + public int Delete(int id) + { + var entity = dbSet.FirstOrDefault(e => e.Id == id); + if (entity == default) + return 0; + dbSet.Remove(entity); + return db.SaveChanges(); + } + } + +}