DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/CrudService.cs

81 lines
2.4 KiB
C#
Raw Normal View History

using AsbCloudApp.Services;
2021-08-02 12:52:44 +05:00
using AsbCloudDb.Model;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
2021-08-02 12:52:44 +05:00
namespace AsbCloudInfrastructure.Services
{
public class CrudService<Tdto, TModel> : ICrudService<Tdto>
2021-08-02 14:45:13 +05:00
where TModel : class, AsbCloudDb.Model.IId
where Tdto : AsbCloudApp.Data.IId
2021-08-02 12:52:44 +05:00
{
private readonly IAsbCloudDbContext context;
2021-08-02 12:52:44 +05:00
private readonly DbSet<TModel> dbSet;
public CrudService(IAsbCloudDbContext context)
2021-08-02 12:52:44 +05:00
{
this.context = context;
2021-08-02 12:52:44 +05:00
dbSet = context.Set<TModel>();
}
public IEnumerable<Tdto> GetAll(System.Linq.Expressions.Expression<System.Func<object, bool>> predicate = null)
2021-08-02 12:52:44 +05:00
{
IQueryable<TModel> entities = dbSet;
2021-08-02 14:45:13 +05:00
if (predicate is not null)
entities = entities.Where(predicate).Cast<TModel>();
2021-08-02 12:52:44 +05:00
var dto = entities.Adapt<Tdto>();
return dto;
}
public Tdto Get(int id)
{
var entity = dbSet.FirstOrDefault(e => e.Id == id);
var dto = entity.Adapt<Tdto>();
return dto;
}
public Tdto Insert(Tdto newItem)
{
var newEntity = newItem.Adapt<TModel>();
var dbEntity = dbSet.Add(newEntity);
context.SaveChanges();
2021-08-02 12:52:44 +05:00
return dbEntity.Entity.Adapt<Tdto>();
}
public IEnumerable<Tdto> InsertRange(IEnumerable<Tdto> newItems)
{
2021-08-02 14:45:13 +05:00
var newEntities = newItems.Adapt<IEnumerable<TModel>>();
2021-08-02 12:52:44 +05:00
var dbEntities = new Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<TModel>[newItems.Count()];
for (int i = 0; i < dbEntities.Length; i++)
dbEntities[i] = dbSet.Add(newEntities.ElementAt(i));
context.SaveChanges();
2021-08-02 12:52:44 +05:00
return dbEntities.Select(e => e.Entity.Adapt<Tdto>());
}
public Tdto Update(Tdto item)
{
var newEntity = item.Adapt<TModel>();
var dbEntity = dbSet.Update(newEntity);
context.SaveChanges();
2021-08-02 12:52:44 +05:00
return dbEntity.Entity.Adapt<Tdto>();
}
public int Delete(int id)
{
var entity = dbSet.FirstOrDefault(e => e.Id == id);
if (entity == default)
return 0;
dbSet.Remove(entity);
return context.SaveChanges();
2021-08-02 12:52:44 +05:00
}
}
}