1

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(); 
    }
  } 
}
9
  • 1
    Maybe you could try extending this instead of base. Commented Sep 21, 2021 at 15:59
  • It might be because you are in a constructor. Does it work outside the constructor? Are you getting a compile error or a runtime error. What is the error? Saying "It doesn't work" doesn't tell us much Commented Sep 21, 2021 at 16:04
  • What happens when you try invoking it like: DbContextExtensions.AreThereAnyChanges(base)? Commented Sep 21, 2021 at 16:09
  • @Marko Radivojević My goal is to write an extension method to DbContext class. Commented Sep 21, 2021 at 16:19
  • 1
    It's good to paste the error text as well. We don't memorize the error codes. In this case, it's "'type' does not contain a definition for 'identifier'" Commented Sep 21, 2021 at 16:41

1 Answer 1

4

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.