How to use SQLite as testing database in EF Core for ASP.NET Core Web API?

41 Views Asked by At

I have an ASP.NET Core Web API project that uses EF core and my SQL for its persistence layer. So I want to test my Web API project using XUnit. But, I would like to use SQLite in-memory database to avoid all efforts to create a fresh database for each test.

So, I have migration C# files those are created based on MySQL but I want to apply them to my SQLite version 3 database.

I am using this code to apply all structures on my database at the start point of the application:

if (!app.Environment.IsProduction())
{
    using (var scope = app.Services.GetRequiredService<IServiceScopeFactory>().CreateScope())
    {
        var dbContext = scope.ServiceProvider.GetService<MyDbContext>();

        if (dbContext.Database.IsRelational() && dbContext.Database.GetMigrations().Any())
        {
            await dbContext.Database.MigrateAsync();
        }
    }
}

And I am using this code to replace the MySQL database with SQLite inside my using IClassFixture:

 UnregisterDependency<DbContextOptions<BordarVmsDbContext>>(services);
 UnregisterDependency<DbConnection>(services);
        
 var connectionString = "DataSource=testDB;mode=memory;cache=shared;";
 var keepAliveConnection = new SqliteConnection(connectionString);
    
 keepAliveConnection.Open();
        
 services.AddDbContext<MyDbContext>( options =>
 {
      options.EnableSensitiveDataLogging(true);
      Dapper.SqlMapper.AddTypeHandler(new GuidHandler());
      options.UseSqlite(keepAliveConnection); 
 });

But I get this error raised when I run my application:

Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 1: 'no such collation sequence: ascii_general_ci'.

How can I use SQLite as my temporary database in testing environment?

0

There are 0 best solutions below