Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is the Seed method called in a EF code first migrations scenario?

Tags:

I'm new in a project and there is this class for the seed data:

 internal sealed class Configuration : DbMigrationsConfiguration<DAL.Context>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }

And this code to start the seed:

protected override void Seed(Context context)
    {
        try
        {

My question is: when is the Seed method called? Only when a user does update-database and the user doesn't have the database (basicly a new user), or also when the user with an existing database calls an update-database?

like image 511
Michel Avatar asked Jun 10 '14 13:06

Michel


People also ask

Which method can be used to seed initial data in database using Entity Framework Core?

Seed Data in Entity Framework Core So as soon as we execute our migration files to create and configure the database, we want to populate it with some initial data. This action is called Data Seeding. So, we are using the HasData method to inform EF Core about the data it has to seed.

What is Code First migrations in Entity Framework?

Code First Migrations is the recommended way to evolve your application's database schema if you are using the Code First workflow. Migrations provide a set of tools that allow: Create an initial database that works with your EF model. Generating migrations to keep track of changes you make to your EF model.

How do you seed data into a database?

Data seeding is the process of populating a database with an initial set of data. There are several ways this can be accomplished in EF Core: Model seed data. Manual migration customization.


1 Answers

When it comes to the migrations Seed() method, coming from DbMigrationsConfiguration class, it's called every time when the Update-Database command is executed. Also when user calls it having existing database.

There is yet another Seed() method - it is a database initializer. It's invoked when database is creating and doesn't handle existing data (while seed from DbMigrationsConfiguration handles them, checking if specified entities exist).

Good to look up to One Unicorn blog for more information.

like image 178
magos Avatar answered Sep 19 '22 22:09

magos