using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using BlueWest.Data; using Microsoft.EntityFrameworkCore; namespace BlueWest.WebApi.EF; public static class GenericExtensions { internal static T GetOne(this DbSet dbSet, Expression> predicate) where T: class => dbSet.FirstOrDefault(predicate); internal static async Task GetOneAsync(this DbSet dbSet, Expression> predicate) where T: class => await dbSet.FirstOrDefaultAsync(predicate); internal static (bool, T) NotFound() where T : class => (false, null); internal static (bool, T) Add(this DbSet dbSet, DbContext dbContext, T objectToAdd) where T: class { var newEntity = dbSet.Add(objectToAdd).Entity; return (dbContext.SaveChanges() >= 0, newEntity); } internal static async Task<(bool, T)> AddAsync(this DbSet dbSet, DbContext dbContext, T objectToAdd) where T: class { var newEntity = dbSet.Add(objectToAdd); bool resultOperation = await dbContext.SaveChangesAsync() >= 0; return (resultOperation, objectToAdd); } internal static (bool, T) Update(this DbSet dbSet, DbContext dbContext, T objectToUpdate) where T: class { dbContext.Update(objectToUpdate); var resultOperation = dbContext.SaveChanges() >= 0; return resultOperation ? (true, objectToUpdate) : (false, null); } internal static async Task<(bool, T)> UpdateAsync(this DbSet dbSet, DbContext dbContext, T objectToUpdate) where T: class { dbSet.Update(objectToUpdate); var result = await dbContext.SaveChangesAsync() >= 0; return (result, objectToUpdate); } }