Entity Framework Core seed data

.net-core c# entity-framework-core

Question

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

1
2
12/27/2018 1:20:16 PM

Accepted Answer

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.

3
12/27/2018 1:34:01 PM

Popular Answer

Create a DataSeeder class and Inject DbContext in it. Write a seedData method to insert the required data. This would be custom logic.

You can run this code after database is created.

public class DataSeeder
{
    public static void SeedRandomPassword(YourDbContext context)
    {
            //// your custom logic to generate random password 
            //// set it to right user


            context.Users.Add();  // Or Update depending on what you need
            context.SaveChanges();
        }
    }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow