4

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

0

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I didn't see ASP.NET Core mentioned anywhere.
My point is the question author didn't mention ASP.NET Core anywhere in the question while your code is designed to be used within ASP.NET Core. But probably you guessed it right. Nevermind.
Oh! Understood! I have guessed from his question tags! :) Thank you.
I did mention .Net Core in the question. Thanks for the answer!
@kjwdamme .NET Core is not the same as ASP.NET Core.
|
0

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();
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.