How can I reset an EF7 InMemory provider between unit tests?

Bit late to the party, but i also ran into the same issue but what i ended up doing was.

Specifying a different database name for each test.

optionsBuilder.UseInMemoryDatabase(Guid.NewGuid().ToString());

That way you dont have to add

_context.Database.EnsureDeleted();

in all your tests


I would go with a combination of both answers. If tests run in parallel, you could have a database being deleted while you are in the middle of running another test, so I was seeing sporadic failures when running a 30+ tests.

Give it a random db name, and ensure it gets deleted when the test is completed.

public class MyRepositoryTests : IDisposable {
  private SchoolContext _context;

  [TestInitialize]
  public void Setup() {
    var options = new DbContextOptionsBuilder<ApplicationDbContext>()
      // Generate a random db name
      .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
      .Options;
      _context = new ApplicationDbContext(options);
  }

  [TestCleanup]
  public void Cleanup()
    _context.Database.EnsureDeleted(); // Remove from memory
    _context.Dispose();
  }
}

The following call will clear the in-memory datastore.

_context.Database.EnsureDeleted();

Simply change your code definition of DbContextOptionsBuilder to be like following :

        var databaseName = "DatabaseNameHere";
        var dbContextOption = new DbContextOptionsBuilder<SchoolContext>()
                                    .UseInMemoryDatabase(databaseName, new InMemoryDatabaseRoot())
                                    .Options;

new InMemoryDatabaseRoot() creates a new database without the issue of Id's persisting. So you don't need now for :

       [TestCleanup]
       public void Cleanup()
       {
           _context = null;
       }