Reputation: 1252
At first, I have an extension method for DbContext class to save with logs :
public static int SaveChangesWithLogging(this DbContext context, NLog.Logger logger)
{
//logging
//[...]
return context.SaveChanges();
}
Then, I have a class which inherit from dbcontext and where I override SaveChanges()
public class ChildDbContext : DbContext
{
public override int SaveChanges()
{
//other stuff
//[...]
//doesn't work, no definition for SaveChangesWithLogging (extension method not found, why ?)
return base.SaveChangesWithLogging();
//doesn't work, loop on SaveChanges by extension method and stack overflow as a result
return base.SaveChangesWithLogging();
}
}
I want to call the SaveChanges() of base DbContext class, but it call SaveChanges() of ChildDbContext or I have a loop and a stack overflow...
What is the good solution ?
Upvotes: 1
Views: 784
Reputation: 152556
The extension method is hiding the real problem is that you're trying to call an overridden method from the outside, which is not possible. Since the actual object is a ChildDbContext
, the overridden method will be called by SaveChangesWithLogging
. There's not a way to call the "base" method from within SaveChangesWithLogging
- even if you cast it before of after the method.
I suggest rearranging your call hierarchy so that the base method can be called from the derived method, or using non-virtual methods so that the base method can be called directly.
Upvotes: 1