using Emergence.data.Contexts; using Emergence.data.Models; using Emergence.models; using Emergence.services.Interface; using System; using System.Collections.Generic; using System.Data.Common; using System.Text; namespace Emergence.services.Services; public static class TenantExtension { public static TenantModel ConvertToTenantModel(this Tenant tenant) { TenantModel model = new TenantModel { Id = tenant.Id, TenantCode = tenant.TenantCode, CompanyName = tenant.CompanyName, IsInactive = tenant.IsInactive, }; return model; } public static Tenant ConvertToTenant(this TenantModel tenant) { Tenant model = new Tenant { Id = tenant.Id.HasValue ? tenant.Id.Value : Guid.NewGuid(), TenantCode = tenant.TenantCode, CompanyName = tenant.CompanyName, IsInactive = tenant.IsInactive, }; return model; } } public class TenantService : ITenantService { private readonly AdminDbContext _dbContext; public TenantService(AdminDbContext dbContext) { _dbContext = dbContext; } public async Task> GetAllAsync() { return _dbContext.Tenant.Select(s => s.ConvertToTenantModel()); } public async Task GetByIdAsync(Guid id) { var entity = _dbContext.Tenant.Where(f => f.Id == id)?.Select(s => s.ConvertToTenantModel()).FirstOrDefault(); return entity; } public async Task CreateAsync(TenantModel model) { if (model.Id == Guid.Empty || model.Id == null) model.Id = Guid.NewGuid(); Tenant newTenant = model.ConvertToTenant(); try { _dbContext.Tenant.Add(newTenant); await _dbContext.SaveChangesAsync(); return model; } catch (DbException ex) { return null; } } }