Skip to content

Instantly share code, notes, and snippets.

@divega
Created May 31, 2019 18:06
Show Gist options
  • Save divega/2419f6496066ae4ca82fce63c219abd9 to your computer and use it in GitHub Desktop.
Save divega/2419f6496066ae4ca82fce63c219abd9 to your computer and use it in GitHub Desktop.
Using a shared in-memory SQLite database in a test
using System;
using System.Linq;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace EnsureCreatedSqliteInMemory
{
class Program
{
static void Main(string[] args)
{
var connectionString = "DataSource=myshareddb;mode=memory;cache=shared";
using (var keepDatabaseAlive = new SqliteConnection(connectionString))
{
keepDatabaseAlive.Open();
var services = new ServiceCollection()
.AddDbContext<MyContext>(options => options.UseSqlite(connectionString))
.BuildServiceProvider();
using (var scope = services.CreateScope())
{
using (var myDb = scope.ServiceProvider.GetRequiredService<MyContext>())
{
var result = myDb.Database.EnsureCreated();
try
{
Console.WriteLine($"Number of rows in the table is {myDb.People.Count()}");
}
catch (Exception e)
{
Console.WriteLine($"Threw exception: {e}");
}
}
}
}
}
}
public class MyContext : DbContext
{
public MyContext(DbContextOptions<MyContext> options) : base(options)
{
}
public DbSet<Person> People { get; set; }
}
public class Person
{
public int Id { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment