The Vanilla Thrilla
The Vanilla Thrilla

Reputation: 2005

Entity Framework Core - Use In Memory Database and fill with fake data

I'm stuck on how to add the DBContext in the Startup.cs. I have the following which doesn't work (but I was finally able to get it to compile). How can I reduce this to using the options I define and using that in my using statement. Obviously I don't want to define two different databases, but this was the only way I could get it to compile. If I'm approaching this the wrong way, please let me know. Here is a sample from ConfigureServices() in Startup.cs

var options = new DbContextOptionsBuilder<ApiContext>().UseInMemoryDatabase(databaseName: "Appointments");
services.AddDbContext<ApiContext>(options => options.UseInMemoryDatabase(databaseName: "Test"));
using (var context = new ApiContext(options.Options))
{
     //Create Fake Data
     DataGenerator.GenerateData(context);
}

Upvotes: 0

Views: 7010

Answers (2)

Yinqiu
Yinqiu

Reputation: 7190

If you want to add fake data to MemoryDatabase,you can do as following.

In your startup:

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApiContext>(opt => opt.UseInMemoryDatabase());
        //...
    }
    //To add data to the in-memory database when the application starts up, add some code to the Configure method:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        //...
        var scopeeee = app.ApplicationServices.CreateScope();
        var context = scopeeee.ServiceProvider.GetRequiredService<ApiContext>();
        AddTestData(context);
        //...
    }

    private static void AddTestData(ApiContext context)
    {
        //add fake data
        //.....
        context.Add(model);
        context.SaveChanges();
    }

Upvotes: 3

Jeremy Lakeman
Jeremy Lakeman

Reputation: 11163

Don't try to create a context during ConfigureServices. There are other command line tools, like ef core, that will create your service provider for other reasons.

Instead I recommend you create an IHostedService, create a service scope and then perform your initialisation.

Upvotes: 0

Related Questions