Using EntityFrameWorkCore and SqlLite in memory I get "no such table: ControlGroup" error

c# entity-framework-core in-memory-database sqlite

Question

The context of my problem is, I want to create some unit tests to my application which executes some relational-specific code, so I can't use the standard .UseInMemoryDatabase(databaseName: dbContextName) I changed it to .UseSqlite("DataSource=:memory:") instead in order to fix that.

But now I get:

SqliteException: SQLite Error 1: 'no such table: ControlGroup'.

How can I fix this?

1
2
4/9/2019 1:53:42 PM

Accepted Answer

You need to keep the connection open within your test scope and create the database.

public class Tests : IDisposable
{
    private readonly SqliteConnection _connection;
    private readonly DbContextOptions _options;

    public Tests()
    {
        _connection = new SqliteConnection("datasource=:memory:");
        _connection.Open();

        _options = new DbContextOptionsBuilder()
            .UseSqlite(_connection)
            .Options;

        using (var context = new MyContext(_options))
            context.Database.EnsureCreated();
    }

    public void Dispose()
    {
        _connection.Close();
    }

    [Fact]
    public void Test()
    {
        using (var context = new MyContext(_options))
        {
            // use in memory database
            context.ControlGroup ...
        }
    } 
}
2
4/10/2019 12:36:01 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow