Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core, Sqlite, InMemory, Code First - just HOW?

I want to create a database with structure from my test model. In memory. Using Sqlite and Entity Framework Core. Of course, code first. I created my model.

Data\DataContext.cs:

using Microsoft.EntityFrameworkCore;

namespace MyTest.Data {

    public class DataContext : DbContext {

        public DbSet<Record> Records { get; set; }

        public DataContext(DbContextOptions options) : base(options) { }

    }

}

Data\Record.cs:

using System;

namespace MyTest.Data {

    public class Record {

        public int Id { get; set; }

        public string Name { get; set; }

        public string Description { get; set; }

        public DateTime Time { get; set; }

    }
}

And I have this test code:

using System;
using System.Data.Common;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;

using MyTest.Data;

namespace MyTest {
    
    public class Startup {
        
        static DbConnection TestDbConnection = new SqliteConnection("Data Source=:memory:;Cache=shared");

        void InitializeTestDatabase() {
            var dbOptions = new DbContextOptionsBuilder().UseSqlite(TestDbConnection).Options;
            var dbContext = new DataContext(dbOptions);
            dbContext.Database.EnsureCreated();
            for (int i = 0; i < 1024; i++) {
                var testString = Guid.NewGuid().ToString();
                dbContext.Records.Add(new Record { Name = testString.Substring(0, 8), Description = testString, Time = DateTime.Now });
            }
            dbContext.SaveChanges();
        }

    }

}

Of course it throws SQL exception, because there is no such table like "Records". Obviously. The structure was normally created with migrations, but I've read you cannot use migrations with InMemory. That I should use EnsureCreated() instead. But then how can I get the structure built from my models code? What am I missing here?

like image 700
Harry Avatar asked Sep 18 '25 14:09

Harry


1 Answers

I've needed to add SqliteConnection.Open call on my connection to make it work:

var conn = new SqliteConnection("DataSource=:memory:");
conn.Open(); // open connection to use

var options = new DbContextOptionsBuilder<VegaDbContext>()
   .UseSqlite(conn)
   .Options;

using (var ctx = new VegaDbContext(options))
{
    ctx.Database.EnsureCreated();
    ctx.Records.ToList();
}
like image 199
Guru Stron Avatar answered Sep 20 '25 03:09

Guru Stron