Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core seed data

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

like image 839
kjwdamme Avatar asked Jan 27 '23 23:01

kjwdamme


1 Answers

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.

like image 84
TanvirArjel Avatar answered Feb 05 '23 21:02

TanvirArjel