Using Entity Framework Core’s InMemory provider

Sri Gunnala
3 min readAug 30, 2019

--

Every time I needed to build a prototype application for a showcase or a demo, I felt the need of in-memory database. Especially when you are sharing your code with someone else, then providing instructions for DB set up and whole application set up is a hassle. As the purpose is just to demonstrate, I do not want to put too much effort in creating and setting up a new database. Entity framework core in-memory database provider solves this problem. When you move the prototype in to actual development stage, you can simply replace in-memory provider with required database provider. No other code changes needed. Let’s check this out with simple example. Step by step guide to use Entity Framework Core’s InMemory provider below.

You can download the sample here — download source

  1. I am using .NET Web API to demonstrate this. Create an empty .NET Core Web API project.
  2. Install Microsoft.EntityFrameworkCore.InMemory nuget package manager
  3. In Startup.cs class register InMemoryDatabase provider.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<GameDbContext>(options => options.UseInMemoryDatabase(databaseName: "Games"));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

4. Create Game model and GameDbContext class

// Game Model class
public class Game
{
public int ID { get; set; }

public string Title { get; set; }

public string Description { get; set; }
}

// Game db context class
public class GameDbContext : DbContext
{
public GameDbContext(DbContextOptions<GameDbContext> options)
: base(options)
{
}

public DbSet<Game> Games { get; set; }
}

5. Create DataGenerator to generate some mock data

public class DataGenerator
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new GameDbContext(
serviceProvider.GetRequiredService<DbContextOptions<GameDbContext>>()))
{
// Look for any board games.
if (context.Games.Any())
{
return; // Data was already seeded
}

context.Games.AddRange(
new Game
{
ID = 1,
Title = "Awe",
Description = "some game"
},
new Game
{
ID = 2,
Title = "Entro",
Description = "kingdom"
});

context.SaveChanges();
}
}
}

6. Now, in Program.cs initialise the data using DataGenerator. Replace Main method code with below

public static void Main(string[] args)
{
//1. Get the IWebHost which will host this application.
var host = CreateWebHostBuilder(args).Build();

//2. Find the service layer within our scope.
using (var scope = host.Services.CreateScope())
{
//3. Get the instance of BoardGamesDBContext in our services layer
var services = scope.ServiceProvider;
var context = services.GetRequiredService<GameDbContext>();

//4. Call the DataGenerator to create sample data
DataGenerator.Initialize(services);
}

//Continue to run the application
host.Run();
}

7. Now add a new controller and scaffold it with actions for Game model. It will generate REST actions to create, read, update, delete and list entities.

simple Get example below

// GET: api/Games/5
[HttpGet("{id}")]
public async Task<ActionResult<Game>> GetGame(int id)
{
var game = await _context.Games.FindAsync(id);
if (game == null)
{
return NotFound();
}
return game;
}

8. All set now to run and use it.

9. Happy coding!!

Down sides of this.

Please note that

  1. Inmemory provider is not recommended for real-time production use
  2. Not recommendable for huge data sets.
  3. Inmemory doesn’t maintain data integrity.

--

--