using LANCommander.Server.Data; using LANCommander.Server.Data.Models; using LANCommander.Server.Models; using Microsoft.EntityFrameworkCore; using System.Linq.Expressions; namespace LANCommander.Server.Services { public abstract class BaseDatabaseService : BaseService where T : BaseModel { public DatabaseContext Context { get; set; } public HttpContext HttpContext { get; set; } public BaseDatabaseService(DatabaseContext dbContext, IHttpContextAccessor httpContextAccessor) : base() { Context = dbContext; HttpContext = httpContextAccessor.HttpContext; } public virtual async Task> Get() { return await Get(x => true).ToListAsync(); } public virtual async Task Get(Guid id) { using (var repo = new Repository(Context, HttpContext)) { return await repo.Find(id); } } public virtual IQueryable Get(Expression> predicate) { using (var repo = new Repository(Context, HttpContext)) { return repo.Get(predicate); } } public virtual bool Exists(Guid id) { return Get(id) != null; } public virtual async Task Add(T entity) { using (var repo = new Repository(Context, HttpContext)) { entity = await repo.Add(entity); await repo.SaveChanges(); 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> AddMissing(Expression> predicate, T entity) { using (var repo = new Repository(Context, HttpContext)) { var existing = repo.Get(predicate).FirstOrDefault(); if (existing == null) { entity = await repo.Add(entity); await repo.SaveChanges(); return new ExistingEntityResult { Value = entity, Existing = false }; } else { return new ExistingEntityResult { Value = existing, Existing = true }; } } } public virtual async Task Update(T entity) { using (var repo = new Repository(Context, HttpContext)) { var existing = await repo.Find(entity.Id); Context.Entry(existing).CurrentValues.SetValues(entity); entity = repo.Update(existing); await repo.SaveChanges(); return entity; } } public virtual async Task Delete(T entity) { using (var repo = new Repository(Context, HttpContext)) { repo.Delete(entity); await repo.SaveChanges(); } } } }