Created
May 31, 2019 18:06
-
-
Save divega/2419f6496066ae4ca82fce63c219abd9 to your computer and use it in GitHub Desktop.
Using a shared in-memory SQLite database in a test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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