LANCommander/LANCommander.Launcher.Services/_BaseDatabaseService.cs
2026-05-14 00:30:45 -05:00

235 lines
7.9 KiB
C#

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Linq.Expressions;
using System.Reflection;
using LANCommander.Launcher.Data;
using LANCommander.Launcher.Data.Models;
using LANCommander.Launcher.Models;
namespace LANCommander.Launcher.Services
{
public abstract class BaseDatabaseService<T> : BaseService where T : BaseModel
{
protected DatabaseContext Context { get; set; }
public BaseDatabaseService(DatabaseContext dbContext, ILogger logger) : base(logger)
{
Context = dbContext;
}
public virtual async Task<ICollection<T>> GetAsync()
{
return await Query(x => true).ToListAsync();
}
public virtual async Task<T> GetAsync(Guid id)
{
return await Context.Set<T>().FindAsync(id);
}
public virtual async Task<T> FirstOrDefaultAsync(Expression<Func<T, bool>> predicate)
{
return await Context.Set<T>().FirstOrDefaultAsync(predicate);
}
public virtual IQueryable<T> Query(Expression<Func<T, bool>> predicate)
{
return Context.Set<T>().Where(predicate);
}
public virtual async Task<bool> ExistsAsync(Guid id) => await Context.Set<T>().AnyAsync(x => x.Id == id);
public virtual async Task<bool> ExistsAsync(Expression<Func<T, bool>> predicate) => await Context.Set<T>().AnyAsync(predicate);
public virtual async Task<T> AddAsync(T entity)
{
var result = await Context.Set<T>().AddAsync(entity);
entity = result.Entity;
if (Context.Database.CurrentTransaction == null)
await Context.SaveChangesAsync();
return entity;
}
/// <summary>
/// Adds an entity to the database if it does exist as dictated by the predicate
/// </summary>
/// <param name="predicate">Qualifier expressoin</param>
/// <param name="entity">Entity to add</param>
/// <returns>Newly created or existing entity</returns>
public virtual async Task<ExistingEntityResult<T>> AddMissingAsync(Expression<Func<T, bool>> predicate, T entity)
{
var existing = await Query(predicate).FirstOrDefaultAsync();
if (existing == null)
{
entity = await AddAsync(entity);
return new ExistingEntityResult<T>
{
Value = entity,
Existing = false,
};
}
else
{
return new ExistingEntityResult<T>
{
Value = entity,
Existing = true,
};
}
}
public virtual async Task<T> UpdateAsync(T entity)
{
var existing = await GetAsync(entity.Id);
Context.Entry(existing).CurrentValues.SetValues(entity);
entity = Context.Update(existing).Entity;
if (Context.Database.CurrentTransaction == null)
await Context.SaveChangesAsync();
return entity;
}
public virtual async Task SyncRelatedCollectionAsync<T, TChild, U>(
T entity,
Expression<Func<T, ICollection<TChild>>> navigationProperty,
IEnumerable<U> records,
Func<U, Expression<Func<TChild, bool>>> matchExpression) where TChild : class where T : class
{
Context.Attach(entity);
var entry = Context.Entry(entity);
var enumerableExpr = Expression.Lambda<Func<T, IEnumerable<TChild>>>(
navigationProperty.Body,
navigationProperty.Parameters);
var collectionEntry = entry.Collection(enumerableExpr);
if (!collectionEntry.IsLoaded)
await collectionEntry.LoadAsync();
var collection = navigationProperty.Compile().Invoke(entity);
if (collection == null)
{
collection = new List<TChild>();
if (navigationProperty.Body is not MemberExpression memberExpression ||
memberExpression.Member is not PropertyInfo propertyInfo)
throw new InvalidOperationException($"Navigation expression '{navigationProperty}' must point to a property.");
propertyInfo.SetValue(entity, collection);
}
var matchedChildren = new HashSet<TChild>();
foreach (var record in records)
{
var matchPredicate = matchExpression(record);
var existingChild = collection.FirstOrDefault(matchPredicate.Compile());
if (existingChild == null)
{
existingChild = await Context.Set<TChild>()
.FirstOrDefaultAsync(matchPredicate);
}
if (existingChild != null)
{
if (!collection.Contains(existingChild))
collection.Add(existingChild);
matchedChildren.Add(existingChild);
}
}
var toDelete = collection
.Where(child => !matchedChildren.Contains(child))
.ToList();
foreach (var child in toDelete)
{
collection.Remove(child);
}
await Context.SaveChangesAsync();
}
public virtual async Task SyncOwnedCollectionAsync<TEntity, TChild>(
TEntity entity,
Expression<Func<TEntity, ICollection<TChild>>> navigationProperty,
IEnumerable<TChild> incomingRecords,
Func<TChild, TChild, bool> matchFunc,
Action<TChild, TChild> updateAction) where TChild : BaseModel where TEntity : class
{
Context.Attach(entity);
var entry = Context.Entry(entity);
var enumerableExpr = Expression.Lambda<Func<TEntity, IEnumerable<TChild>>>(
navigationProperty.Body,
navigationProperty.Parameters);
var collectionEntry = entry.Collection(enumerableExpr);
if (!collectionEntry.IsLoaded)
await collectionEntry.LoadAsync();
var collection = navigationProperty.Compile().Invoke(entity);
if (collection == null)
{
collection = new List<TChild>();
if (navigationProperty.Body is not MemberExpression memberExpression ||
memberExpression.Member is not PropertyInfo propertyInfo)
throw new InvalidOperationException($"Navigation expression '{navigationProperty}' must point to a property.");
propertyInfo.SetValue(entity, collection);
}
var matched = new HashSet<TChild>();
foreach (var incoming in incomingRecords)
{
var existing = collection.FirstOrDefault(c => matchFunc(c, incoming));
if (existing != null)
{
updateAction(existing, incoming);
matched.Add(existing);
}
else
{
collection.Add(incoming);
matched.Add(incoming);
}
}
var toRemove = collection.Where(c => !matched.Contains(c)).ToList();
foreach (var child in toRemove)
{
collection.Remove(child);
Context.Set<TChild>().Remove(child);
}
await Context.SaveChangesAsync();
}
public virtual async Task DeleteAsync(T entity)
{
Context.Set<T>().Remove(entity);
if (Context.Database.CurrentTransaction == null)
await Context.SaveChangesAsync();
}
}
}