public async Task<int> AddOrderAsync(CreateOrderModel model, User user)
{
int affectedRows = 0;
var level = IsolationLevel.Serializable;
using (var transaction = _ctx.Database.BeginTransaction(level))
{
try
{
int lastId = await GetLastId();
Orders Orders = CreteOrders(model, lastId);
user.Orders.Add(Orders);
using (var crypto = new RNGCryptoServiceProvider())
{
int retries = 5;
do
{
var pk = crypto.CreateNumberBetween(100000000000000, 1000000000000000);
Orders.CodEst = pk;
foreach (var item in Orders.OrderItems)
item.RoaCodEst = pk;
try
{
affectedRows = await _ctx.SaveChangesAsync();
}
catch (DbUpdateException) when (--retries >= 0)
{
}
catch (Exception ex)
{
string[] parametri = new string[] { model.Codcli, model.Divisione, model.Codage };
if (affectedRows == 0) throw new OrderNotSavedException(ex, parametri);
}
} while (affectedRows == 0);
}
transaction.Commit();
return affectedRows;
}
catch (Exception ex)
{
string[] parametri = new string[] { model.Codcli, model.Divisione, model.Codage };
throw new OrderNotSavedException(ex, parametri);
}
}
}
private static Ordcli CreteOrders(CreateOrderModel model, int lastId)
{
return new Order
{
Id = 0000000000000000,
Anno = model.Anno,
...,
OrderItems = model.OrderItems.Select((item) => new Righe
{
Id = lastId,
CodartVar = item.Codvar == null ? item.Codart : item.Codart + "/" + item.Codvar,
Codart = item.Codart,
Codvar = item.Codvar,
Descri = item.Descri,
Quanti = item.Quanti,
Prezzo = item.Prezzo,
Implor = item.Quanti * item.Prezzo,
Numrig = item.Numrig,
CodEst = 0000000000000000
}).ToList()
};
}
public async Task DeleteOrder(long id)
{
var ordine = await _ctx.Ordine.SingleOrDefaultAsync(x => x.CodEst == id);
_ctx.Ordcli.Remove(ordine);
await _ctx.SaveChangesAsync();
}
public async Task SoftDelete(long id)
{
var ordine = await _ctx.Ordine.SingleOrDefaultAsync(x => x.CodEst == id);
ordine.Deleted = 1;
_ctx.Ordine.Update(ordine);
await _ctx.SaveChangesAsync();
}
Non faccio update ma solo insert e delete/soft-delete
Ho testato con una softdelete (cancellare l'ordine) e ha rifarlo uguale senza nessun errore
Modificato da jjchuck il 07 ottobre 2020 08:47 -
Modificato da jjchuck il 07 ottobre 2020 08:50 -