EF Core: use sqlite for tests with 2 different contexts

Viewed 233

I've started using EF Core for the 1st time with asp.net core and I must confess that I'm not finding the experience that good (specially if you're coming from NH). Now, I've got the following scenario:

  • 2 different DbContexts and each context uses different schemas
  • the API has been set up so that some API operation are wrapped by a transaction (in practice, everything has been set up so that there's a single sqlconnection that's shared by both contexts)

I'd like to test these kind of methods, but I'm not sure on the best approach...After reading the docs, it looks like the best option is using SQLite, but there's a small gotach: setting up the db.

The docs say that I can use the context.Database.EnsureCreated method. Unfortunately, that will only work if the in memory db hasn't been created yet. In other words, after calling if from the 1st context instance, it won't do anything when called over the 2nd context instance (because both context share the same db and it has already been created after the 1st call). In practice, this means that I'll end up with a partial db that has the tables mapped to the entities of the 1st context.

Is there a way to force the creation of the 2nd context tables? Ie, can I write something like this with EF Core:

contextA.Database.EnsureCreated();
contextB.Database.JustCreateTheTablesPlease();

Or do I need to recreate my db from a SQL script before running my tests?

Thanks.

0 Answers
Related