Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 439
RagnaRock Avatar asked Jan 27 '23 11:01

RagnaRock


1 Answers

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 ...
        }
    } 
}
like image 118
Jan Paolo Go Avatar answered Jan 29 '23 11:01

Jan Paolo Go