Nella mia applicazione web asp.net, sto registrando le eccezioni al database. DbConext.SaveChanges
ad ora tutto funziona DbConext.SaveChanges
ma il problema è che quando DbConext.SaveChanges
nel try block genera un'eccezione, non è possibile registrare l'eccezione nel database come DbConext.SaveChanges
nel catch block
anche la stessa eccezione.
Ecco il codice che ho provato finora:
try
{
_unitOfWork.Repository<Product>().InsertEntity(product);
await _unitOfWork.SaveChangesAsync();//This throws exception due the model validation failure
}
catch (Exception exception)
{
ExceptionModel exceptionModel = new ExceptionModel();
using (MyDbContext dbContext = new MyDbContext())
{
await dbContext.ExceptionModels.AddAsync(exceptionModel);
await dbContext.SaveChangesAsync(); // Throws the same exception that was thrown in try block due to entity framework transaction
}
}
Nota: immagino che il problema sia causato dalla transazione Entity Framework.
Si prega di aiutare come posso superare questa situazione per registrare l'eccezione al database. Grazie!
In Entity framework Core, ho risolto il problema facilmente utilizzando la transazione EF-Core
try
{
_unitOfWork.Repository<Product>().InsertEntity(product);
await _unitOfWork.SaveChangesAsync();//This throws exception due the model validation failure
}
catch (Exception exception)
{
ExceptionModel exceptionModel = new ExceptionModel();
string connectionString = _configuration.GetConnectionString("MyConnection");
var options = new DbContextOptionsBuilder<MyDbContext>()
.UseSqlServer(new SqlConnection(connectionString))
.Options;
using (var dbContext = new MyDbContext(options))
{
using (var transaction = dbContext.Database.BeginTransaction())
{
try
{
dbContext.Exceptions.Add(exceptionModel);
await dbContext.SaveChangesAsync();
transaction.Commit();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
}
Nel blocco try si aggiungono alcune modifiche al contesto db. Durante il salvataggio hai ottenuto qualche eccezione e hai utilizzato lo stesso contesto db nel blocco catch per registrare quell'eccezione. Qui il contesto db ha ancora modifiche non salvate fatte nel blocco try. Quindi otterrai la stessa eccezione durante il salvataggio del contesto.
Per evitare ciò, devi eliminare le modifiche dal contesto db nel blocco catch prima di aggiungere altre modifiche.
private void ResetContextState() => _context.ChangeTracker.Entries()
.Where(e => e.Entity != null && e.state == EntityState.Added).ToList()
.ForEach(e => e.State = EntityState.Detached);
Modifica: il codice sopra ha funzionato per me.