Skip to content

Instantly share code, notes, and snippets.

@divega divega/Program.cs
Created May 31, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.