Use an in-memory database in EF Core 7

This is the minimal setup to use an in-memory datase in EF Core 7 with a Console program. C# solution can be found here.

After creating your C# Net Core 7 Console App project add two nuget packages to the project:

Install Package Microsoft.EntityFrameworkCore
Install Package Microsoft.EntityFrameworkCore.InMemory

Next add a class Person to your console project

internal class Person
{
    public int Id { get; set; }

    [Required]
    public string FirstName { get; set; } = string.Empty;
    [Required]
    public string LastName { get; set; } = string.Empty;
}

Next add your database context class, remember to derive it from DbContext.

internal class MyDatabaseContext : DbContext
{
    public DbSet<Person> Persons { get; set; }

    public MyDatabaseContext(DbContextOptions<MyDatabaseContext> options) : base(options)
    {
    }
}

Now we can use our database context in the main program as shown below

MyDatabaseContext db = new MyDatabaseContext(
    new DbContextOptionsBuilder<MyDatabaseContext>().UseInMemoryDatabase("TEST").Options);

db.Persons.Add(new Person() {  FirstName = "Berend", LastName = "de Jong"});
db.SaveChanges();
db.Persons.ForEachAsync((person) => Console.WriteLine($"{person.Id}\t{person.FirstName}\t{person.LastName}"));

As an alternative you can use a parameterless constructor and override the OnConfiguring method of the DbContext class to configure your connection.

Remove the options parameter from the constructor and the call to the base constructor. Next override the OnConfiguring method of the DbContext as shown below.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseInMemoryDatabase("TEST");
}
Share

Leave a Reply

Your email address will not be published. Required fields are marked *