InMemory database

From Logic Wiki
Jump to: navigation, search


Install

dotnet add package Microsoft.EntityFrameworkCore 8.*
dotnet add package Microsoft.EntityFrameworkCore.InMemory

program.cs

using Microsoft.EntityFrameworkCore;
.....
.....

builder.Services.AddDbContext<AppDbContext>(options =>
  options.UseInMemoryDatabase("PeopleDb"));


builder.Services.AddScoped<IPersonRepository, PersonRepository>();

they must be before var app = builder.Build();

Entites/Person.cs

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public int Age { get; set; }
}

Repositories

Repositories/AppDbContext

using api_sandbox.Entities;
using Microsoft.EntityFrameworkCore;

....
....

public class AppDbContext : DbContext
{
  public AppDbContext(DbContextOptions<AppDbContext> options)
    : base(options)
  {
  }
  public DbSet<Person> People => Set<Person>();
}

Repositories/IPersonRepository

public interface IPersonRepository
{
    Task<List<Person>> GetAll();

    Task<Person> Create(string name, int age);
}

Repositories/PersonRepository

public class PersonRepository(AppDbContext dbContext) : IPersonRepository
{
    public async Task<List<Person>> GetAll()
    {
       return await dbContext.People.ToListAsync();
    }

    public async Task<Person> Create(string name, int age)
    {
        var person = new Person {Name = name, Age = age};
        dbContext.People.Add(person);
        await dbContext.SaveChangesAsync();
        return person;
    }
}

Controller

public class HomeController(IPersonRepository personRepository) : Controller
{
...
    [HttpGet("add")]
    public async Task<IActionResult>  AddPerson()
    {
        await personRepository.Create("John", 30);
        await personRepository.Create("Jane", 25);
        return Ok("OK");    
    }

    [HttpGet("get")]
    public async Task<IActionResult> GetPerson()
    {
        return Ok(await personRepository.GetAll());
    }
}