session-companion/SessionCompanion/SessionCompanion.Services/Base/ServiceBase.cs

74 lines
2.1 KiB
C#

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();
}
}
}