Home > Blockchain >  Writing DbContext extension method
Writing DbContext extension method

Time:09-22

When I write DbContext extension method, It doesn't work. I can't access to the method from DbContext object. What is the problem ?

namespace Data
{
 public static class DbContextExtensions
 {
    public static bool AreThereAnyChanges(this DbContext context)
        => context.ChangeTracker
            .Entries()
            .Any(x => x.State == EntityState.Modified ||
                      x.State == EntityState.Added ||
                      x.State == EntityState.Deleted);
 }
}

using Data;
namespace Demo
{
 public partial class KybInfrastructureDemoDbContext : DbContext, IDatabaseContext
 {
    public KybInfrastructureDemoDbContext() { }

    public KybInfrastructureDemoDbContext(DbContextOptions<KybInfrastructureDemoDbContext> options)
        : base(options) { 
           // 'DbContext' does not contain a definition for 'AreThereAnyChanges'
           bool change = base.AreThereAnyChanges(); 
    }
  } 
}

CodePudding user response:

base is not an object reference. It is a keyword to force the compiler to bind to a base class member instead of an override on the current class. Since there is no AreThereAnyChanges defined on the base class, the compiler throws an error.

Use this instead. And since this is a DbContext, the compiler should find the appropriate extension method:

bool change = this.AreThereAnyChanges();

Note that if there were also an AreThereAnyChanges extension method specific to KybInfrastructureDemoDbContext, then you could still bind to the DbContext extention by casting this:

bool change = ((DbContext)this).AreThereAnyChanges();
  • Related