So I have a Entity Framework Core first database and a .Net Core application.
I want to add Seed Data to it when creating the database. I know the FluentAPI has the HasData method but that is not what i am looking for.
When the database gets created I want to create a user with a random generated password (that is different every time) that will be saved on a file in the server.
I can't use the HasData method because then it will create the same password everytime.
So my question is: Is there a way, other than the HasData method, to add Seed data to a Entity Framework Core Code First database
Yes! There is a way! You can do as follows:
public static class DatabaseInitializer
{
public static void Initialize(YourDbContext dbContext)
{
dbContext.Database.EnsureCreated();
if (!dbContext.Users.Any())
{
// Write you necessary to code here to insert the User to database and save the the information to file.
}
}
}
The in the Configure
method of the Startup
class as follows:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, YourDbContext dbContext)
{
// other configurations
..............
DatabaseInitializer.Initialize(dbContext);
..............
// other configurations
}
Initialize
method will be called only once during the application start up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With