59 lines
1.8 KiB
C#
59 lines
1.8 KiB
C#
using System.Reflection;
|
|
using DBConnection.Models;
|
|
using DBConnection.Repositories.Interfaces;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using NuGet.Configuration;
|
|
|
|
namespace DBConnection.Repositories;
|
|
|
|
public abstract class BaseRepository<TEntityType> : IRepository<TEntityType> where TEntityType : BaseEntity
|
|
{
|
|
protected readonly AppDbContext DbContext;
|
|
|
|
private object?[]? GetPrimaryKey(TEntityType entity)
|
|
{
|
|
var keyProperties = DbContext.Model.FindEntityType(typeof(TEntityType))?.FindPrimaryKey()?.Properties.Select(p => p.Name);
|
|
return keyProperties?.Select(p => entity.GetType().GetProperty(p)?.GetValue(entity, null)).ToArray();
|
|
}
|
|
|
|
protected abstract IQueryable<TEntityType> GetAllIncludedQueryable();
|
|
|
|
public BaseRepository(AppDbContext dbContext)
|
|
{
|
|
DbContext = dbContext;
|
|
}
|
|
|
|
public virtual TEntityType Delete(TEntityType entity)
|
|
{
|
|
DbContext.Set<TEntityType>().Remove(entity);
|
|
return entity;
|
|
}
|
|
|
|
public virtual async Task<TEntityType> Upsert(TEntityType entity)
|
|
{
|
|
bool exists = await DbContext.Set<TEntityType>().ContainsAsync(entity);
|
|
if (!exists)
|
|
{
|
|
DbContext.Set<TEntityType>().Add(entity);
|
|
}
|
|
else
|
|
{
|
|
var dbEntry = await Get(entity);
|
|
DbContext.Entry(dbEntry).CurrentValues.SetValues(entity);
|
|
}
|
|
|
|
await DbContext.SaveChangesAsync();
|
|
return entity;
|
|
}
|
|
|
|
public virtual async Task<TEntityType?> Get(TEntityType entity)
|
|
{
|
|
var keyValues = GetPrimaryKey(entity);
|
|
return await Get(keyValues);
|
|
}
|
|
|
|
public virtual async Task<TEntityType?> Get(params object?[]? keyValues)
|
|
{
|
|
return await DbContext.Set<TEntityType>().Include(j => j.DateCreated).FindAsync(keyValues);
|
|
}
|
|
} |