using LANCommander.Launcher.Data; using LANCommander.Launcher.Data.Models; using LANCommander.Launcher.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using System.Linq.Expressions; namespace LANCommander.Launcher.Services { public abstract class BaseDatabaseService : BaseService where T : BaseModel { protected DatabaseContext Context { get; set; } public BaseDatabaseService(DatabaseContext dbContext, SDK.Client client, ILogger logger) : base(client, logger) { Context = dbContext; } public virtual async Task> GetAsync() { return await Query(x => true).ToListAsync(); } public virtual async Task GetAsync(Guid id) { return await Context.Set().FindAsync(id); } public virtual IQueryable Query(Expression> predicate) { return Context.Set().Where(predicate); } public virtual bool Exists(Guid id) { return GetAsync(id) != null; } public virtual async Task AddAsync(T entity) { var result = await Context.Set().AddAsync(entity); entity = result.Entity; await Context.SaveChangesAsync(); return entity; } /// /// Adds an entity to the database if it does exist as dictated by the predicate /// /// Qualifier expressoin /// Entity to add /// Newly created or existing entity public virtual async Task> AddMissingAsync(Expression> predicate, T entity) { var existing = await Query(predicate).FirstOrDefaultAsync(); if (existing == null) { entity = await AddAsync(entity); return new ExistingEntityResult { Value = entity, Existing = false, }; } else { return new ExistingEntityResult { Value = entity, Existing = true, }; } } public virtual async Task UpdateAsync(T entity) { var existing = await GetAsync(entity.Id); Context.Entry(existing).CurrentValues.SetValues(entity); entity = Context.Update(existing).Entity; await Context.SaveChangesAsync(); return entity; } public virtual async Task DeleteAsync(T entity) { Context.Set().Remove(entity); await Context.SaveChangesAsync(); } } }