I am creating a website using Asp.net core .
I wanted to know that is it a good and safe way to add admins of site to database using seed data ?
if not , how should i do this ?
You can create an extension method for adding user into data base and call method in program.cs
file or in configure
method in startup
class
According to Microsoft documentation better way is use this to using seed data
Program.cs
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<DbContext>();
DbInitializer.Initialize(context);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while seeding the database.");
}
}
host.Run();
}
or Configure method way
public static void Initialize(this IApplicationBuilder app)
{
using (var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var dbContext = scope.ServiceProvider.GetServices<DbContext>();
//insert data in database
}
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Initialize();
}
and this link can be helpful for seeding admin user