86 lines
1.5 KiB
C#
86 lines
1.5 KiB
C#
namespace MyOffice.Data.Repositories;
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
|
using DbContext;
|
|
|
|
public class RepositoryBase<TEntity> where TEntity : class
|
|
{
|
|
//TODO: Rename
|
|
protected readonly AppDbContext _context;
|
|
|
|
protected RepositoryBase(
|
|
AppDbContext context
|
|
)
|
|
{
|
|
_context = context;
|
|
}
|
|
|
|
protected async Task<int> SaveChangesAsync()
|
|
{
|
|
try
|
|
{
|
|
return await _context.SaveChangesAsync();
|
|
}
|
|
catch (DbUpdateException updateException)
|
|
{
|
|
throw updateException;
|
|
}
|
|
}
|
|
|
|
protected int SaveChanges()
|
|
{
|
|
try
|
|
{
|
|
return _context.SaveChanges();
|
|
}
|
|
catch (DbUpdateException updateException)
|
|
{
|
|
throw updateException;
|
|
}
|
|
}
|
|
|
|
|
|
protected async Task<TEntity?> GetBaseAsync(Guid id)
|
|
{
|
|
return await _context.Set<TEntity>().FindAsync(id);
|
|
}
|
|
|
|
protected TEntity? GetBase(Guid id)
|
|
{
|
|
return _context.Set<TEntity>().Find(id);
|
|
}
|
|
|
|
protected int AddBase(TEntity entity)
|
|
{
|
|
//_context.Add(entity);
|
|
_context.Entry(entity).State = EntityState.Added;
|
|
|
|
var result = SaveChanges();
|
|
|
|
_context.Entry(entity).State = EntityState.Detached;
|
|
return result;
|
|
}
|
|
|
|
protected int RemoveBase(TEntity entity)
|
|
{
|
|
_context.Set<TEntity>().Remove(entity);
|
|
|
|
_context.Entry(entity).State = EntityState.Deleted;
|
|
|
|
var result = SaveChanges();
|
|
|
|
_context.Entry(entity).State = EntityState.Detached;
|
|
return result;
|
|
}
|
|
|
|
protected int UpdateBase(TEntity entity)
|
|
{
|
|
//_context.Attach(entity);
|
|
_context.Entry(entity).State = EntityState.Modified;
|
|
|
|
var result = SaveChanges();
|
|
|
|
_context.Entry(entity).State = EntityState.Detached;
|
|
return result;
|
|
}
|
|
} |