How to manage the scope of db context in .NET Core when SaveChanges() fails

.net-core asp.net-core c# entity-framework-core

Question

An Azure service bus queue initiates a.NET Core console application that we have. According to what I understand, the DbContext's default lifespan when used with DI isScoped and thus rather than employing lifetime management, it is advised to allow DI and the framework do itusing statements. However, in the instance below, when we callSaveChanges() We attempt calling it again to write a log to the database when it fails. What's the best course of action in this case? Using it feels strange.using when DI injects the context into the caller class.

try
{
    db.Add(new MyEntity());
    db.SaveChanges();
}
catch (Exception ex) // a constraint is violated
{
    db.Add(new LogEntity("Unable to save MyEntity"));
    db.SaveChanges(); // this fails because MyEntity is still in scope of the context
}
1
0
9/24/2019 1:10:01 AM

Popular Answer

ZZZ_tmp
0
9/24/2019 5:44:24 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow