Files
DaSaSo/DaSaSo.EntityFramework/Services/Common/NonQueryDataService.cs
2021-09-30 16:27:28 +02:00

55 lines
1.8 KiB
C#

using DaSaSo.Domain.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DaSaSo.EntityFramework.Services.Common
{
class NonQueryDataService<T> where T: DomainObject
{
private readonly DaSaSoDbContextFactory _contextFactory;
public NonQueryDataService(DaSaSoDbContextFactory contextFactory)
{
_contextFactory = contextFactory;
}
public async Task<T> Create(T entity)
{
using DaSaSoDbContext context = _contextFactory.CreateDbContext();
EntityEntry<T> createdEntity = await context.Set<T>().AddAsync(entity);
await context.SaveChangesAsync();
return createdEntity.Entity;
}
public T CreateNonAsync(T entity)
{
using DaSaSoDbContext context = _contextFactory.CreateDbContext();
EntityEntry<T> createdEntity = context.Set<T>().Add(entity);
context.SaveChanges();
return createdEntity.Entity;
}
public async Task<bool> Delete(int id)
{
using DaSaSoDbContext context = _contextFactory.CreateDbContext();
T entity = await context.Set<T>().FirstOrDefaultAsync((e) => e.Id == id);
context.Set<T>().Remove(entity);
await context.SaveChangesAsync();
return true;
}
public async Task<T> Update(int id, T entity)
{
using DaSaSoDbContext context = _contextFactory.CreateDbContext();
entity.Id = id;
context.Set<T>().Update(entity);
await context.SaveChangesAsync();
return entity;
}
}
}