CodeLiturgy.Dashboard/BlueWest.Api/Context/Extensions/GenericExtensions.cs

51 lines
1.8 KiB
C#
Raw Normal View History

2022-08-22 00:14:50 +03:00
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<T>(this DbSet<T> dbSet, Expression<Func<T,bool>> predicate) where T: class => dbSet.FirstOrDefault(predicate);
internal static async Task<T> GetOneAsync<T>(this DbSet<T> dbSet, Expression<Func<T,bool>> predicate) where T: class => await dbSet.FirstOrDefaultAsync(predicate);
internal static (bool, T) NotFound<T>() where T : class => (false, null);
internal static (bool, T) Add<T>(this DbSet<T> 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<T>(this DbSet<T> 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<T>(this DbSet<T> 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<T>(this DbSet<T> dbSet, DbContext dbContext, T objectToUpdate) where T: class
{
dbSet.Update(objectToUpdate);
var result = await dbContext.SaveChangesAsync() >= 0;
return (result, objectToUpdate);
}
}