C
C#2y ago
Kamil Pisz

Looking solution for get query from _dbContext.SaveChangesAsync() for save logs and easier debugging

Hello, i have a .net core 6.0 app that save entites in MSSQL database with EfCORE 6.0 so my function is something like
var newInvoice = new Invoice();
newInvoice.Name = "2022/12/12"
newInvoice.Value = 5m;
await _dbContext.Invoices.AddAsync(newInvoice);
await _SaveChangesAsync();

var newInvoiceProduct = new InvoiceProduct();
newInvoiceProduct.Name = "toy1"
newInvoiceProduct.Value = 5m;
await _dbContext.InvoicesProduct.AddAsync(newInvoiceProduct);
await _SaveChangesAsync();
var newInvoice = new Invoice();
newInvoice.Name = "2022/12/12"
newInvoice.Value = 5m;
await _dbContext.Invoices.AddAsync(newInvoice);
await _SaveChangesAsync();

var newInvoiceProduct = new InvoiceProduct();
newInvoiceProduct.Name = "toy1"
newInvoiceProduct.Value = 5m;
await _dbContext.InvoicesProduct.AddAsync(newInvoiceProduct);
await _SaveChangesAsync();
What i want to do: every Add/Modify query that going to DB should create new Log in my Logging table
var newInvoice = new Invoice();
newInvoice.Name = "2022/12/12"
newInvoice.Value = 5m;
await _dbContext.Invoices.AddAsync(newInvoice);
await _SaveChangesAsync();

//Save logs what SQL send to database or save expcetion/error message
var newInvoiceLog = new InvoiceLog();
newInvoiceLog.InvoiceId = newInvoice.Id; // id of new created entity
newInvoiceLog.RawQuery = //<----- that i missing, single string that going to DB like Logging to debug console
var newInvoice = new Invoice();
newInvoice.Name = "2022/12/12"
newInvoice.Value = 5m;
await _dbContext.Invoices.AddAsync(newInvoice);
await _SaveChangesAsync();

//Save logs what SQL send to database or save expcetion/error message
var newInvoiceLog = new InvoiceLog();
newInvoiceLog.InvoiceId = newInvoice.Id; // id of new created entity
newInvoiceLog.RawQuery = //<----- that i missing, single string that going to DB like Logging to debug console
2 Replies
FusedQyou
FusedQyou2y ago
DbContext.SaveChanges(async) can be overridden. Override it, get the added/changed/deleted entities and log them event EventHandler<SavingChangesEventArgs>? SavingChanges also exists in dbContext. And event EventHandler<SavedChangesEventArgs>? SavedChanges.
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server