forked from ddrilling/AsbCloudServer
+
This commit is contained in:
parent
4d08e0e562
commit
d5d52daa53
81
AsbCloudInfrastructure/Services/CrudService.cs
Normal file
81
AsbCloudInfrastructure/Services/CrudService.cs
Normal file
@ -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<Tdto, TModel>
|
||||||
|
where TModel : class, IId
|
||||||
|
{
|
||||||
|
private readonly DbContext context;
|
||||||
|
private readonly IAsbCloudDbContext db;
|
||||||
|
private readonly DbSet<TModel> dbSet;
|
||||||
|
|
||||||
|
public CrudService(IAsbCloudDbContext db)
|
||||||
|
{
|
||||||
|
this.db = db;
|
||||||
|
dbSet = context.Set<TModel>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public IEnumerable<Tdto> GetAll(System.Linq.Expressions.Expression< System.Func<TModel, bool>> predicate = null)
|
||||||
|
{
|
||||||
|
IQueryable<TModel> entities = dbSet;
|
||||||
|
|
||||||
|
if(predicate is not null)
|
||||||
|
entities = entities.Where(predicate);
|
||||||
|
|
||||||
|
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);
|
||||||
|
db.SaveChanges();
|
||||||
|
return dbEntity.Entity.Adapt<Tdto>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public IEnumerable<Tdto> InsertRange(IEnumerable<Tdto> newItems)
|
||||||
|
{
|
||||||
|
var newEntities = newItems.Adapt< IEnumerable<TModel>>();
|
||||||
|
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));
|
||||||
|
|
||||||
|
db.SaveChanges();
|
||||||
|
return dbEntities.Select(e => e.Entity.Adapt<Tdto>());
|
||||||
|
}
|
||||||
|
|
||||||
|
public Tdto Update(Tdto item)
|
||||||
|
{
|
||||||
|
var newEntity = item.Adapt<TModel>();
|
||||||
|
var dbEntity = dbSet.Update(newEntity);
|
||||||
|
db.SaveChanges();
|
||||||
|
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 db.SaveChanges();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user