using FMDAL.DTO.AssetState; using FMDAL.Query.AssetState; using GB5Shared.DTO.Framework.Login; using GB5Shared.GB5Exception; using GB5Shared.QueryExecutor; using Microsoft.Data.SqlClient; using System; using System.Collections.Generic; using System.Data.Common; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace FMDAL.CustomCode.AssetState { public class AssetStateDAL : IAssetStateDAL { private readonly IQueryExecutor _qe; public AssetStateDAL(IQueryExecutor qe) => _qe = qe; public async Task GetAssetState(int assetStateId, LoginDTO login, CancellationToken ct) { var items = await _qe.QueryAsync(login, AssetStateQB.GET_ASSETSTATE, new { AssetStateId = assetStateId, TenantId = login.ClientId }, cancellationToken: ct).ConfigureAwait(false); return items.FirstOrDefault(); } public async Task> GetAssetStateListByType(int assetTypeId, LoginDTO login, CancellationToken ct) { return await _qe.QueryAsync(login, AssetStateQB.GET_ASSETSTATE_LIST_BY_TYPE, new { AssetTypeId = assetTypeId, TenantId = login.ClientId }, cancellationToken: ct).ConfigureAwait(false); } public async Task SaveAssetState(AssetStateDTO dto, LoginDTO login, DbTransaction tx, CancellationToken ct) { try { await _qe.ExecuteAsync(login, AssetStateQB.SAVE_ASSETSTATE, dto, tx, cancellationToken: ct).ConfigureAwait(false); return dto.AssetStateId; } catch (SqlException ex) when (ex.Number == 2627 || ex.Number == 2601) { throw new DatabaseOperationException( $"AssetState with StateCode '{dto.AssetStateCode}' already exists for AssetTypeId {dto.AssetTypeId}.", ex); } } public async Task UpdateAssetState(AssetStateDTO dto, LoginDTO login, DbTransaction tx, CancellationToken ct) { try { await _qe.ExecuteAsync(login, AssetStateQB.UPDATE_ASSETSTATE, dto, tx, cancellationToken: ct).ConfigureAwait(false); } catch (SqlException ex) when (ex.Number == 2627 || ex.Number == 2601) { throw new DatabaseOperationException( $"AssetState with StateCode '{dto.AssetStateCode}' already exists for AssetTypeId {dto.AssetTypeId}.", ex); } } public async Task DeleteAssetState(int assetStateId, int modifiedById, LoginDTO login, DbTransaction tx, CancellationToken ct) { await _qe.ExecuteAsync(login, AssetStateQB.DELETE_ASSETSTATE, new { AssetStateId = assetStateId, ModifiedById = modifiedById, ModifiedOn = DateTime.UtcNow, TenantId = login.ClientId }, tx, cancellationToken: ct).ConfigureAwait(false); } } }