Search code examples
c#sqliteentity-framework-corein-memory-database

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?


Solution

  • 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 ...
            }
        } 
    }