using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AyCode.Core.Extensions; using AyCode.Core.Helpers; using AyCode.Database.DbContexts; using AyCode.Database.Extensions; using AyCode.Entities; using AyCode.Interfaces; using AyCode.Interfaces.Entities; using AyCode.Utils.Extensions; using Microsoft.EntityFrameworkCore; namespace AyCode.Database.DataLayers; public abstract class AcDalBase : IAcDalBase where TDbContext : AcDbContextBase { public string Name { get; private set; } public bool AutoCloseSession { get; set; } /// /// Do not use it! Use Session or Transaction... - J. /// public TDbContext Context { get; private set; } public Mutex MutextLock { get; } = new(); //protected AcDalBase() //{ // Name = $"{GetType().Name}"; //} protected AcDalBase() : this(Activator.CreateInstance()) { } protected AcDalBase(TDbContext ctx) { Context = ctx; if (Context.Name.IsNullOrWhiteSpace()) Context.Name = Context.GetType().Name; Name = $"{GetType().Name}, {Context.Name}"; } public TDbContext CreateDbContext() { return Activator.CreateInstance(); } public void CloseDbContext(ref TDbContext? ctx) { ctx?.Dispose(); ctx = null; } public TModelDto? GetModelDtoById(Guid id) where TModelDto : class, IAcModelDtoBase where TEntity : class, IEntity => Session(ctx => ctx.GetModelDtoById(id)); public Task GetModelDtoByIdAsync(Guid id) where TModelDto : class, IAcModelDtoBase where TEntity : class, IEntity => SessionAsync(ctx => ctx.GetModelDtoById(id)); public List GetAllModelDto() where TModelDto : class, IAcModelDtoBase where TEntity : class, IEntity => Session(ctx => ctx.GetAllModelDto().ToList()); public Task> GetAllModelDtoAsync() where TModelDto : class, IAcModelDtoBase where TEntity : class, IEntity => SessionAsync(ctx => ctx.GetAllModelDto().ToList()); public Task SessionAsync(Func callback) => this.SessionAsync(callback); public Task> SessionAsync(Func> callback) where TEntity : IEntity => this.SessionAsync(callback); public TResultType Session(Func callback) => this.Session(callback); public IEnumerable Session(Func> callback) where TEntity : IEntity => this.Session(callback); public Task TransactionAsync(Func callbackTransactionBody, bool throwException = false) => this.TransactionAsync(callbackTransactionBody, throwException); public bool Transaction(Func callbackTransactionBody, bool throwException = false) => this.Transaction(callbackTransactionBody, throwException); public override string ToString() { return Name; } //public void Dispose() //{ // Ctx?.Dispose(); // Ctx = null; // //CloseDbContext(ref Ctx); //} }