Search code examples
c#asp.netentity-framework-core

How to implement DbContext as an interface? Final goal is to use Moq for Unit testing


This is my non-working code so far. I have done all research that my understanding allows. I might be missing something silly. I am new to c# and .Net environment.

Everything is good with the LibraryContext class. The problem is that I can not make use of the interface. When I load it to as services in Startup.cs and then call it in the controllers it gives errors. Updating the question with Startup.cs and BooksController.cs snippets.

First error is in LibraryContext.cs:

LibraryContext' does not implement interface member 'ILibraryContext.SaveChangesAsync()' [LibraryApi].

And then in BooksController.cs :

'ILibraryContext' does not contain a definition for 'Entry' and no accessible extension method 'Entry' accepting a first argument of type 'ILibraryContext' could be found (are you missing a using directive or an assembly reference?) [LibraryApi]csharp(CS1061)

...

LibraryContext.cs

public interface ILibraryContext : IDisposable
  {
    public DbSet<Reader> Readers { get; set; }
    public DbSet<Book> Books { get; set; }

    Task<int> SaveChangesAsync();
  }


  public class LibraryContext : DbContext, ILibraryContext
  {
    public LibraryContext(DbContextOptions<LibraryContext> options)
          : base(options)
    {
    }

    public virtual DbSet<Reader> Readers { get; set; }
    public virtual DbSet<Book> Books { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
      modelBuilder.Entity<Book>().ToTable("Book");
      modelBuilder.Entity<Reader>().ToTable("Reader");
    }
  }

Startup.cs

    {
      services.AddScoped<ILibraryContext>(provider => provider.GetService<LibraryContext>());
    ...
    }

BooksController.cs

  {
    private readonly ILibraryContext _context;

    public BooksController(ILibraryContext context)
    {
      _context = context;
    }
...

Solution

  • No, not everything is good with the 'LibraryContext' class. The clue is in the errormessage: LibraryContext' does not implement interface member 'ILibraryContext.SaveChangesAsync()' .

    You could add it like this:

    async Task<int> SaveChangesAsync() => await base.SaveChangesAsync();

    or

    async Task<int> SaveChangesAsync() => base.SaveChangesAsync();