I want to write a query When the program first runs, query Add values to the database?
I want this query to run only once
What is the best solution?
As far as I know, if you want to run dbcontext when the application started, I suggest you could try to asp.net core lifetime method to run codes in the Configure method.
More details, you could refer to below codes:
In the startup.cs Configure method add below codes:
lifetime.ApplicationStarted.Register(
() => AddLogs(app));
Addlogs method:
static void AddLogs(IApplicationBuilder app)
{
using (var serviceScope = app.ApplicationServices.CreateScope())
{
//Check the table or role is exsited or not to make sure below codes will just start once.
if (true)
{
var context = serviceScope.ServiceProvider.GetService<TestDbcontext>();
var list = context.Admissions.ToList();
//dbcontext.Admissions.Add(new Admission() { });
context.SaveChanges();
}
}
}
Result:
Update:
lifetime is a parameter which we could passed to the startup.cs Configure method:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments