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);
}
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();
}