LANCommander/LANCommander.Server.Data/Repository.cs

445 lines
13 KiB
C#
Raw Normal View History

using LANCommander.SDK.Extensions;
using LANCommander.SDK;
using LANCommander.Server.Data.Models;
using Microsoft.AspNetCore.Http;
2023-01-02 15:44:04 -06:00
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
2023-01-02 15:44:04 -06:00
using System.Linq.Expressions;
using System.Threading;
using AutoMapper.QueryableExtensions;
using AutoMapper;
2023-01-02 15:44:04 -06:00
2024-08-04 18:44:33 -05:00
namespace LANCommander.Server.Data
2023-01-02 15:44:04 -06:00
{
2024-10-15 23:48:16 -05:00
public class Repository<T> : IDisposable where T : class, IBaseModel
2023-01-02 15:44:04 -06:00
{
public readonly DatabaseContext Context;
private readonly IMapper Mapper;
2024-10-14 00:59:54 -05:00
private readonly IHttpContextAccessor HttpContextAccessor;
private readonly ILogger Logger;
2023-01-02 15:44:04 -06:00
private List<Expression<Func<T, object>>> IncludeExpressions { get; } = new();
private User User;
private bool Tracking = true;
public Repository(
DatabaseContext context,
IMapper mapper,
IHttpContextAccessor httpContextAccessor,
ILogger<Repository<T>> logger)
2023-01-02 15:44:04 -06:00
{
Context = context;
Mapper = mapper;
2024-10-14 00:59:54 -05:00
HttpContextAccessor = httpContextAccessor;
Logger = logger;
Logger?.LogDebug("Opened up context {ContextId}", Context.ContextId);
2023-01-02 15:44:04 -06:00
}
private DbSet<T> DbSet
{
get { return Context.Set<T>(); }
}
private DbSet<User> UserDbSet
{
get { return Context.Set<User>(); }
}
private IQueryable<T> Query(Expression<Func<T, bool>> predicate)
2023-01-02 15:44:04 -06:00
{
using (var op = Logger.BeginOperation("Querying database"))
{
var queryable = DbSet.AsQueryable().Where(predicate);
foreach (var includeExpression in IncludeExpressions)
{
queryable = queryable.Include(includeExpression);
}
op.Complete();
if (!Tracking)
queryable = queryable.AsNoTracking();
return queryable;
}
2023-01-02 15:44:04 -06:00
}
public Repository<T> AsNoTracking()
{
Tracking = false;
return this;
}
public Repository<T> Include(Expression<Func<T, object>> includeExpression)
{
IncludeExpressions.Add(includeExpression);
return this;
}
public async Task <ICollection<T>> GetAsync(Expression<Func<T, bool>> predicate)
2023-01-02 15:44:04 -06:00
{
try
{
2024-11-08 00:39:55 -06:00
await Context.ContextMutex.WaitAsync();
return await Query(predicate).ToListAsync();
}
finally
{
Tracking = true;
IncludeExpressions.Clear();
Context.ContextMutex.Release();
}
}
public async Task<ICollection<U>> GetAsync<U>(Expression<Func<T, bool>> predicate)
{
try
{
await Context.ContextMutex.WaitAsync();
return await Query(predicate).ProjectTo<U>(Mapper.ConfigurationProvider).ToListAsync();
}
finally
{
Tracking = true;
IncludeExpressions.Clear();
2024-11-08 00:39:55 -06:00
Context.ContextMutex.Release();
}
}
public async Task<T> FirstAsync(Expression<Func<T, bool>> predicate)
{
try
{
2024-11-08 00:39:55 -06:00
await Context.ContextMutex.WaitAsync();
return await Query(predicate).FirstAsync();
}
finally
{
Tracking = true;
IncludeExpressions.Clear();
Context.ContextMutex.Release();
}
}
public async Task<U> FirstAsync<U>(Expression<Func<T, bool>> predicate)
{
try
{
await Context.ContextMutex.WaitAsync();
return await Query(predicate).ProjectTo<U>(Mapper.ConfigurationProvider).FirstAsync();
}
finally
{
Tracking = true;
IncludeExpressions.Clear();
2024-11-08 00:39:55 -06:00
Context.ContextMutex.Release();
}
}
public async Task<T> FirstAsync<TKey>(Expression<Func<T, bool>> predicate, Expression<Func<T, TKey>> orderKeySelector)
{
try
{
2024-11-08 00:39:55 -06:00
await Context.ContextMutex.WaitAsync();
return await Query(predicate).OrderByDescending(orderKeySelector).FirstAsync();
}
finally
{
Tracking = true;
IncludeExpressions.Clear();
Context.ContextMutex.Release();
}
}
public async Task<U> FirstAsync<U, TKey>(Expression<Func<T, bool>> predicate, Expression<Func<U, TKey>> orderKeySelector)
{
try
{
await Context.ContextMutex.WaitAsync();
return await Query(predicate).ProjectTo<U>(Mapper.ConfigurationProvider).OrderByDescending(orderKeySelector).FirstAsync();
}
finally
{
Tracking = true;
IncludeExpressions.Clear();
2024-11-08 00:39:55 -06:00
Context.ContextMutex.Release();
}
}
public async Task<T> FindAsync(Guid id)
{
try {
2024-11-08 00:39:55 -06:00
await Context.ContextMutex.WaitAsync();
using (var op = Logger.BeginOperation("Finding entity with ID {EntityId}", id))
{
var entity = await Query(x => x.Id == id).FirstAsync();
op.Complete();
return entity;
}
}
finally
{
Tracking = true;
IncludeExpressions.Clear();
Context.ContextMutex.Release();
}
}
public async Task<U> FindAsync<U>(Guid id)
{
try
{
await Context.ContextMutex.WaitAsync();
using (var op = Logger.BeginOperation("Finding entity with ID {EntityId}", id))
{
var entity = await Query(x => x.Id == id).ProjectTo<U>(Mapper.ConfigurationProvider).FirstAsync();
op.Complete();
return entity;
}
}
finally
{
Tracking = true;
IncludeExpressions.Clear();
2024-11-08 00:39:55 -06:00
Context.ContextMutex.Release();
}
2023-01-02 15:44:04 -06:00
}
public async Task<T> FirstOrDefaultAsync(Expression<Func<T, bool>> predicate)
2023-01-02 15:44:04 -06:00
{
try
{
2024-11-08 00:39:55 -06:00
await Context.ContextMutex.WaitAsync();
using (var op = Logger.BeginOperation("Getting first or default of type {EntityType}", typeof(T).Name))
{
var entity = await Query(predicate).FirstOrDefaultAsync();
op.Complete();
return entity;
}
}
finally
{
Tracking = true;
IncludeExpressions.Clear();
Context.ContextMutex.Release();
}
}
public async Task<U> FirstOrDefaultAsync<U>(Expression<Func<T, bool>> predicate)
{
try
{
await Context.ContextMutex.WaitAsync();
using (var op = Logger.BeginOperation("Getting first or default of type {EntityType}", typeof(T).Name))
{
var entity = await Query(predicate).ProjectTo<U>(Mapper.ConfigurationProvider).FirstOrDefaultAsync();
op.Complete();
return entity;
}
}
finally
{
Tracking = true;
IncludeExpressions.Clear();
2024-11-08 00:39:55 -06:00
Context.ContextMutex.Release();
}
}
public async Task<T> FirstOrDefaultAsync<TKey>(Expression<Func<T, bool>> predicate, Expression<Func<T, TKey>> orderKeySelector)
{
try
{
2024-11-08 00:39:55 -06:00
await Context.ContextMutex.WaitAsync();
return await Query(predicate).OrderByDescending(orderKeySelector).FirstOrDefaultAsync();
}
finally
{
Tracking = true;
IncludeExpressions.Clear();
Context.ContextMutex.Release();
}
}
public async Task<U> FirstOrDefaultAsync<U, TKey>(Expression<Func<T, bool>> predicate, Expression<Func<U, TKey>> orderKeySelector)
{
try
{
await Context.ContextMutex.WaitAsync();
return await Query(predicate).ProjectTo<U>(Mapper.ConfigurationProvider).OrderByDescending(orderKeySelector).FirstOrDefaultAsync();
}
finally
{
Tracking = true;
IncludeExpressions.Clear();
2024-11-08 00:39:55 -06:00
Context.ContextMutex.Release();
}
2023-01-02 15:44:04 -06:00
}
public async Task<T> AddAsync(T entity)
2023-01-02 15:44:04 -06:00
{
try
{
var currentUser = await GetCurrentUserId();
2024-11-08 00:39:55 -06:00
await Context.ContextMutex.WaitAsync();
2023-01-02 15:44:04 -06:00
using (var op = Logger.BeginOperation("Adding entity of type {EntityType}", typeof(T).Name))
{
entity.CreatedById = currentUser;
entity.UpdatedById = currentUser;
entity.CreatedOn = DateTime.UtcNow;
entity.UpdatedOn = DateTime.UtcNow;
2023-01-02 15:44:04 -06:00
await Context.AddAsync(entity);
op.Complete();
return entity;
}
}
finally
{
Tracking = true;
2024-11-08 00:39:55 -06:00
Context.ContextMutex.Release();
}
2023-01-02 15:44:04 -06:00
}
public async Task<T> UpdateAsync(T entity)
2023-01-02 15:44:04 -06:00
{
try
{
var currentUserId = await GetCurrentUserId();
var existing = await FindAsync(entity.Id);
2024-11-08 00:39:55 -06:00
await Context.ContextMutex.WaitAsync();
using (var op = Logger.BeginOperation("Updating entity with ID {EntityId}", entity.Id))
{
Context.Entry(existing).CurrentValues.SetValues(entity);
WIP fix for MySQL connection concurrency issues This is a large commit. There are a number of things that this commit does to try to fix various issues that were occurring when the database provider was set to MySQL: - The DAL `Repository` has been completely refactored to follow best practices. The repository is now being injected into services instead of the database context itself. This allows the DI to handle the repository's lifetime instead of creating a new repository for every transaction and sharing the context across repositories. As part of these changes, there is no more allowed usage of `IQueryable` and all service/repository methods must actually execute database queries before their return. This is to ensure that the context does not stay open longer than it needs to. Abusing `IQueryable`s by tossing them into Blazor components seems to be a big no-no. - Some deletion behaviors on relationships have been tweaked as MySQL wasn't able to apply migrations with behaviors that were contradictory. - A `ConnectionInterceptor` was added to try to keep track of `DatabaseContext` lifetimes. This is really only for debugging and should be put into `#if DEBUG` regions. This helped identify some potential issues where some contexts were basically never closing, causing the MySQL connector to not function. - Docs for generating migrations have been updated to reflect the addition of being able to specify the database provider and connection string when adding a migration, avoiding the need to edit `Settings.yml` - The application can now be put into a pause state on startup by adding the `--debugger` argument when used from the command line. When a debugger is attached, it resumes execution. - The application can now log to Seq when using debug build - Service lifetime on `DatabaseContext` has switched to transient. This may be reverted in the future. - Lazy loading has been disabled for debugging purposes. It didn't directly help the concurrency issues, but it needs to be tested individually to be re-enabled. - All usage of `UserManager`, `RoleManager`, and `SignInManager` have been removed from all controllers, pages, and Blazor components. Functionality has been moved to `UserService` and `RoleService`. This might have done the most amount of help, but could probably be improved upon in the future by not relying on them and instead having our own implementation. - Application startup migrations and server autostarts have been disabled temporarily. There might be an issue of `DatabaseContext` lifetimes that spawn from this.
2024-10-13 20:42:45 -05:00
entity.UpdatedById = currentUserId;
entity.UpdatedOn = DateTime.UtcNow;
2023-01-02 15:44:04 -06:00
Context.Update(entity);
op.Complete();
2023-01-02 15:44:04 -06:00
return entity;
}
}
finally
{
Tracking = true;
2024-11-08 00:39:55 -06:00
Context.ContextMutex.Release();
}
2023-01-02 15:44:04 -06:00
}
public void Delete(T entity)
{
try
{
2024-11-08 00:39:55 -06:00
Context.ContextMutex.Wait();
using (var op = Logger.BeginOperation("Deleting entity with ID {EntityId}", entity.Id))
{
Context.Remove(entity);
op.Complete();
}
}
finally
{
Tracking = true;
2024-11-08 00:39:55 -06:00
Context.ContextMutex.Release();
}
}
public async Task SaveChangesAsync()
2023-01-02 15:44:04 -06:00
{
try
{
2024-11-08 00:39:55 -06:00
await Context.ContextMutex.WaitAsync();
using (var op = Logger.BeginOperation("Saving changes!"))
{
await Context.SaveChangesAsync();
op.Complete();
}
}
finally
{
Tracking = true;
2024-11-08 00:39:55 -06:00
Context.ContextMutex.Release();
}
2023-01-02 15:44:04 -06:00
}
private async Task<User> GetUser(string username)
2023-01-02 15:44:04 -06:00
{
try
{
2024-11-08 00:39:55 -06:00
await Context.ContextMutex.WaitAsync();
return await UserDbSet.FirstOrDefaultAsync(u => u.UserName == username);
}
finally
{
Tracking = true;
2024-11-08 00:39:55 -06:00
Context.ContextMutex.Release();
}
2023-01-02 15:44:04 -06:00
}
private async Task<Guid?> GetCurrentUserId()
2023-01-02 15:44:04 -06:00
{
2024-10-14 00:59:54 -05:00
if (HttpContextAccessor?.HttpContext?.User?.Identity?.IsAuthenticated == true)
2023-01-02 15:44:04 -06:00
{
if (User == null)
User = await GetUser(HttpContextAccessor.HttpContext.User.Identity.Name);
2023-01-02 15:44:04 -06:00
if (User == null)
return null;
2023-01-02 15:44:04 -06:00
else
return User.Id;
2023-01-02 15:44:04 -06:00
}
2024-10-14 00:59:54 -05:00
else
return null;
2023-01-02 15:44:04 -06:00
}
public void Dispose()
{
try
{
2024-11-08 00:39:55 -06:00
Context.ContextMutex.Release();
Logger?.LogDebug("Disposed context {ContextId}", Context.ContextId);
}
catch {
Logger?.LogDebug("Could not dispose context {ContextId}", Context.ContextId);
}
}
2023-01-02 15:44:04 -06:00
}
}