Added base interface and service

This commit is contained in:
Karol Górzyński 2020-12-05 21:46:27 +01:00
parent e2b55ada11
commit 4aea17277a
3 changed files with 92 additions and 8 deletions

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace SessionCompanion.Services.Base
{
public interface IServiceBase<TViewModel, TEntity> : IDisposable
{
IEnumerable<TViewModel> Get();
Task<TViewModel> Get(int id);
Task<IEnumerable<TEntity>> Get(Expression<Func<TEntity, bool>> expresssion);
Task Create(TViewModel viewModel);
Task Update(int id, TViewModel viewModel);
Task Delete(int id);
Task SaveAsync();
}
}

View File

@ -0,0 +1,73 @@
using SessionCompanion.Database.Tables;
using System;
using System.Collections.Generic;
using System.Text;
using AutoMapper;
using System.Threading.Tasks;
using SessionCompanion.Database.Repositories.Base;
using System.Linq.Expressions;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace SessionCompanion.Services.Base
{
public class ServiceBase<TViewModel, TEntity> : IServiceBase<TViewModel, TEntity> where TEntity : BaseEntity
{
protected IMapper Mapper { get; private set; }
protected IRepository<TEntity> Repository { get; private set; }
public ServiceBase(IMapper mapper, IRepository<TEntity> repository)
{
Mapper = mapper;
Repository = repository;
}
public virtual IEnumerable<TViewModel> Get()
{
var models = Repository.Get();
return Mapper.Map<IEnumerable<TViewModel>>(models);
}
public virtual async Task<TViewModel> Get(int id)
{
var result = await Repository.Get(id);
return Mapper.Map<TViewModel>(result);
}
public virtual async Task<IEnumerable<TEntity>> Get(Expression<Func<TEntity, bool>> expression)
{
var result = await Repository.Get(expression).ToListAsync();
return result;
}
public virtual async Task Create(TViewModel viewModel)
{
var model = Mapper.Map<TEntity>(viewModel);
await Repository.Create(model);
}
public virtual async Task Update(int id, TViewModel viewModel)
{
var model = Mapper.Map<TEntity>(viewModel);
model.Id = id;
await Repository.Update(model);
}
public virtual async Task Delete(int id)
{
var model = await Repository.Get(id);
Repository.Delete(model);
}
public virtual async Task SaveAsync()
{
await Repository.Save();
}
public virtual void Dispose()
{
Repository.Dispose();
}
}
}

View File

@ -1,8 +0,0 @@
using System;
namespace SessionCompanion.Services
{
public class Class1
{
}
}