The EF Core in-memory provider lets an application use EF Core without setting up a separate database. It is useful for learning the entity and context workflow, but its data is not durable: use it only for development, not for a service that must retain data after shutdown. EF Core documentation also recommends against using it for unit or integration testing. section 5.2
Listing 5.1 Creating ManningBooks project with in-memory database
dotnet new console -n ManningBooks cd ManningBooks dotnet add package Microsoft.EntityFrameworkCore.InMemory
Create a console application and add the Microsoft.EntityFrameworkCore.InMemory package before configuring a context. section 5.2
Listing 5.3 A DbContext that holds the Book class
using Microsoft.EntityFrameworkCore;
namespace ManningBooks;
public class CatalogContext : DbContext #1
{
public DbSet<Book> Books { get; set; } #2
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseInMemoryDatabase("ManningBooks"); #3
}
The context exposes Book entities through DbSet<Book> and selects the provider with UseInMemoryDatabase("ManningBooks"). EF Core recognizes Book.Id as a primary key by convention. section 5.2
Listing 5.5 Adding Books to CatalogContext and getting ordered list
using ManningBooks;
using var dbContext = new CatalogContext(); #1
dbContext.Add(new Book { Title = ".NET in Action" }); #2
dbContext.Add(new Book { Title = "API Design Patterns" }); #3
dbContext.Add(new Book { Title = "Grokking Simplicity" });
dbContext.Add(new Book { Title = "The Programmer's Brain" });
dbContext.SaveChanges(); #4
foreach (var book in dbContext.Books.OrderBy(b => b.Id)) #5
{
Console.WriteLine($"\"{book.Title}\" has id {book.Id}"); #6
}
Add books, call SaveChanges, then query the DbSet to print them in ID order. This exercises the ordinary EF Core workflow without a separate database. section 5.2
Do not mistake this provider for an in-memory SQL database. It stores entities in memory as they are, supports neither SQL nor file storage, and therefore cannot demonstrate the disk and network costs that make asynchronous database access valuable. SQLite’s in-memory mode is a different option: it still uses SQL. For SQL and file-backed behavior, replace the InMemory package with Microsoft.EntityFrameworkCore.Sqlite and configure UseSqlite instead. section 5.3
