jeudi 24 octobre 2019

InMemoryDbContext doesn't persist after seed, collection in controller always empty

Inside TestStartup I'm overriding ConfigureDatabase method so I can use InMemory for my tests.

public class TestStartup : Startup
{
    public override void ConfigureDb(IServiceCollection services)
    {
        services.AddDbContext<CarContext>(options => options.UseInMemoryDatabase(Guid.NewGuid().ToString()));
        services.AddTransient<DbSeeder>();
    }
    public override void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            base.Configure(app, env);
            using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
            {
                var dbSeeder = serviceScope.ServiceProvider.GetService<DbSeed>();
                dbSeeder.Seed();
            }
        }
}

public class DbSeed
{
    private readonly CarContext _context;

    public DbSeed(ContactContext context)
    {
       _context = context;
    }

    public void Seed()
    {
        _context.Cars.AddRange(DataGenerator.Cars);
        _context.SaveChanges();
    }
 }

Inside DbSeed class _context.SaveChanges saves the data (it returns > 0 in debug) yet in the Controller ICarService (which uses CarContext) have empty collection of Car DbSet (InMemoryDbContext is used).

Aucun commentaire:

Enregistrer un commentaire