{"id":48600,"date":"2019-08-12T08:02:22","date_gmt":"2019-08-12T06:02:22","guid":{"rendered":"https:\/\/code-maze.com\/?p=48600"},"modified":"2024-05-22T12:45:04","modified_gmt":"2024-05-22T10:45:04","slug":"migrations-and-seed-data-efcore","status":"publish","type":"post","link":"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/","title":{"rendered":"Migrations and Seed Data With Entity Framework Core"},"content":{"rendered":"<p>In this section, we are going to cover Migrations and Seed data features in Entity Framework Core.<\/p>\n<p>In the previous parts of this series, we have created the <strong>database model<\/strong> (entity and context classes) and applied different configuration options. Now it is time to transfer this database model to the real database in the SQL server. Our SQL database schema needs to be aligned with our application\u2019s database model and using migrations will help us keep things that way.<\/p>\n<div style=\"padding: 20px; border-left: 5px color:#dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for the video, visit our <a href=\"https:\/\/www.patreon.com\/posts\/source-code-core-104647903?src=MigrationsEFCore\" target=\"_blank\" rel=\"nofollow noopener\">Patreon page<\/a> (YouTube Patron tier).<\/div>\n<p>EF Core provides a method called <code>Migrate<\/code> to execute migration actions for us. All we have to do is to create model classes, and a context class, apply configuration (which we already did) and create and execute migrations with the set of simple commands.<\/p>\n<p>Let&#8217;s dive in.<\/p>\n<hr \/>\r\n<p style=\"text-align: center;\"><strong>VIDEO<\/strong>: EF Core Code First Migrations in Detail.<\/p>\r\n<p style=\"text-align: center;\"><iframe width=\"560\" height=\"315\" src=https:\/\/www.youtube.com\/embed\/v6mneb01HBM?si=UxRshdfOqNl2lC8D frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen=\"allowfullscreen\"><\/iframe><\/p>\r\n<hr \/>\n<h2 id=\"creatingandapplyingmigrations\">What is Migration in EF Core?<\/h2>\n<p>Using migrations is a standard way to create and update a database with Entity Framework Core. The migration process has two steps: Creating migration and Applying migration. As we already said, our database schema must be aligned with the database model and every change in a database model needs to be migrated to the database itself.<\/p>\n<p>Those changes might for example be:<\/p>\n<ul>\n<li>Changes in the properties of the model class<\/li>\n<li>Configuration changes<\/li>\n<li>Adding or removing the <code>DbSet&lt;T&gt;<\/code> properties from the context class<\/li>\n<\/ul>\n<p>From ASP.NET Core 3.0, EF Core tools required for migrations are not preinstalled. Therefore, we have to install the <code>Microsoft.EntityFrameworkCore.Tools<\/code> library. If you are following this series from the start, then you already have the <code>Microsoft.EntityFrameworkCore<\/code> library installed.<\/p>\n<h2 id=\"creatingandapplyingmigrations\">Creating and Applying Migrations in EF Core<\/h2>\n<p>To create a migration, we can use Visual Studio\u2019s Package Manager Console window or the command window (Windows command prompt). For the PMC window, the command is:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">Add-Migration MigrationName [options]<\/code><\/p>\n<p>Or through the dotnet CLI:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">dotnet ef migrations add MigrationName [options]<\/code><\/p>\n<p>In our application, we are going to use the PMC, so let\u2019s do that by typing:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">PM&gt; Add-Migration InitialMigration<\/code><\/p>\n<p>After we press the Enter key, our migration will be completed.<\/p>\n<h3>Actions that Take Place Behind the Scene<\/h3>\n<p>After we execute the <code>Add-Migration<\/code> command EF Core does several things behind the scenes to prepare our migration. The first thing it does is inspect our class, associated entity classes (in this case only the <code>Student<\/code> class), and any configuration we applied. After that, it creates three different files in the <code>Migrations<\/code> folder:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/08-Migrations-folder.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-48602\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/08-Migrations-folder.png\" alt=\"Migrations-folder\" width=\"333\" height=\"89\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/08-Migrations-folder.png 333w, https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/08-Migrations-folder-300x80.png 300w\" sizes=\"auto, (max-width: 333px) 100vw, 333px\" \/><\/a><\/p>\n<p>The <code>ApplicationContextModelSnapshot.cs<\/code> file holds the model of the database and it is updated every time a new migration is added. The other two files: <code>InitialMigration<\/code> and <code>InitialMigration.Designer<\/code> are files that contain and describe the newly created migration.<\/p>\n<p>So, if you have followed all the steps from the previous articles, the content of the <code>InitialMigration<\/code> file should look like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public partial class InitialMigration : Migration\r\n{\r\n    protected override void Up(MigrationBuilder migrationBuilder)\r\n    {\r\n        migrationBuilder.CreateTable(\r\n            name: \"Student\",\r\n            columns: table =&gt; new\r\n            {\r\n                StudentId = table.Column&lt;Guid&gt;(nullable: false),\r\n                Name = table.Column&lt;string&gt;(maxLength: 50, nullable: false),\r\n                Age = table.Column&lt;int&gt;(nullable: true),\r\n                IsRegularStudent = table.Column&lt;bool&gt;(nullable: false, defaultValue: true)\r\n            },\r\n            constraints: table =&gt;\r\n            {\r\n                table.PrimaryKey(\"PK_Student\", x =&gt; x.StudentId);\r\n            });\r\n    }\r\n\r\n    protected override void Down(MigrationBuilder migrationBuilder)\r\n    {\r\n        migrationBuilder.DropTable(\r\n            name: \"Student\");\r\n    }\r\n}\r\n<\/pre>\n<p>This file has two methods conveniently named <code>Up()<\/code> and <code>Down<\/code>. The <code>Up()<\/code> method consists of commands that will be executed when we apply this migration. As an opposite action, the <code>Down()<\/code> method will execute commands when we remove this migration (in this case it will just drop this created table).<\/p>\n<h3>Applying Created Migration<\/h3>\n<p>After we have successfully created our migration, we have to apply it for changes to take effect in the database. There are several ways of applying migrations (Using SQL scripts, using <code>Database.Migrate<\/code> method, or using command line methods), and as we did with the creation, we are going to use the command line methods approach.<\/p>\n<p>For the Package Manager Console, the command is :<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">Update-Database [options]<\/code><\/p>\n<p>For the command prompt window, the command is:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">dotnet ef database update [options]<\/code><\/p>\n<p>Since we already decided on PMC, let\u2019s open the PMC window and execute the command:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">PM&gt; Update-Database<\/code><\/p>\n<p>After we press the Enter key, we are going to see all the different actions EF Core does for us to apply created migration. As a result, we are going to have our <code>Student<\/code> table created with all the provided configuration from the previous articles:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/09-Migrations-Applied.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-48603\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/09-Migrations-Applied.png\" alt=\"Migrations applied\" width=\"304\" height=\"234\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/09-Migrations-Applied.png 304w, https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/09-Migrations-Applied-300x231.png 300w\" sizes=\"auto, (max-width: 304px) 100vw, 304px\" \/><\/a><\/p>\n<p>There are few more important facts we have to know about EF Core\u2019s migrations. If we inspect our database, we are going to find another created table: <code>_EFMigrationsHistory<\/code>. EF Core uses this table to track all the applied migrations. So, this means that if we create another migration in our code and apply it, EF Core will apply only the newly created migration.<\/p>\n<p>But how does EF Core know what migration needs to be applied?<\/p>\n<p>Well, it stores a unique Id in the\u00a0<code>_EFMigrationsHistory<\/code>, which is a unique name of the migration file created with the migration, and never executes files with the same name again:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/10-EFCoreMigrations-table.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-48604\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/10-EFCoreMigrations-table.png\" alt=\"EFCoreMigrations table\" width=\"1280\" height=\"214\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/10-EFCoreMigrations-table.png 1280w, https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/10-EFCoreMigrations-table-300x50.png 300w, https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/10-EFCoreMigrations-table-768x128.png 768w, https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/10-EFCoreMigrations-table-1024x171.png 1024w, https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/10-EFCoreMigrations-table-1080x181.png 1080w\" sizes=\"auto, (max-width: 1280px) 100vw, 1280px\" \/><\/a><\/p>\n<p>Each migration is applied within an SQL transaction, which means that whole migration either succeeds or fails. If we have multiple migrations to apply, then they will be applied in the exact order they are created.<\/p>\n<h2 id=\"addingcustomcode\">Adding a Custom Code in a Migration File<\/h2>\n<p>We have already explained the purpose of the <code>Up()<\/code> and <code>Down()<\/code> methods in our <code>InitialMigration<\/code> file. But all the code in those methods is generated by EF Core. If needed, we can add our custom code, too. We can use the <code>MigrationBuilder<\/code> parameter to access the broad range of methods that can help us in the process. One of those methods is the <code>Sql<\/code> method that we can use to add the custom code we like.<\/p>\n<p>So, let\u2019s open the <code>InitialMigration<\/code> class and modify it by adding our custom code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"19-21,29\">public partial class InitialMigration : Migration\r\n{\r\n    protected override void Up(MigrationBuilder migrationBuilder)\r\n    {\r\n        migrationBuilder.CreateTable(\r\n            name: \"Student\",\r\n            columns: table =&gt; new\r\n            {\r\n                StudentId = table.Column&lt;Guid&gt;(nullable: false),\r\n                Name = table.Column&lt;string&gt;(maxLength: 50, nullable: false),\r\n                Age = table.Column&lt;int&gt;(nullable: true),\r\n                IsRegularStudent = table.Column&lt;bool&gt;(nullable: false, defaultValue: true)\r\n            },\r\n            constraints: table =&gt;\r\n            {\r\n                table.PrimaryKey(\"PK_Student\", x =&gt; x.StudentId);\r\n            });\r\n\r\n        migrationBuilder.Sql(@\"CREATE PROCEDURE MyCustomProcedure\r\n                               AS\r\n                               SELECT * FROM Student\");\r\n    }\r\n\r\n    protected override void Down(MigrationBuilder migrationBuilder)\r\n    {\r\n        migrationBuilder.DropTable(\r\n            name: \"Student\");\r\n\r\n        migrationBuilder.Sql(@\"DROP PROCEDURE MyCustomProcedure\");\r\n    }\r\n}\r\n<\/pre>\n<p>We should make sure to have the SQL method in the <code>Down()<\/code> method to execute the opposite actions if we decide to remove our migration.<\/p>\n<p>Now, we can delete our database (just to simulate the initial state in the SQL server) and only apply our migration again (we don\u2019t need to create it, it is already created).<\/p>\n<h2 id=\"migrationsinseparateproject\">Creating Migration if Entities and Dbcontext Files are in a Separate Project<\/h2>\n<p>Right now, our model and context classes are in the main project together with the migration files. But in many real-life projects, models and context classes are in a separate project (<a href=\"https:\/\/code-maze.com\/net-core-web-development-part4\/\" target=\"_blank\" rel=\"noopener noreferrer\">repository pattern might be one of the reasons for example<\/a>). For such projects, executing migrations couldn\u2019t be possible with the setup we have in our project.<\/p>\n<p>Let\u2019s try to demonstrate what we mean.<\/p>\n<p>The first thing to do is to create another .NET Core Class Library project and name it <code>Entities<\/code> and install <code>Microsoft.EntityFrameworkCore<\/code> and <code>Microsoft.EntityFrameworkCore.Relational packages<\/code> via NuGet Package Manager or PMC window:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">PM&gt; Install-Package Microsoft.EntityFrameworkCore\r\nPM&gt;Install-Package Microsoft.EntityFrameworkCore.Relational<\/pre>\n<p>Then we need to add the reference to the <code>Entities<\/code> project in our main project.<\/p>\n<p>After that, let\u2019s copy the <code>ApplicationContext<\/code> and the <code>Student<\/code> classes, paste them in the <code>Entities<\/code> project and remove the <code>Entities<\/code> folder from the main project. Our structure should look like this:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/New-Project-Structure.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-50091 size-full\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/New-Project-Structure.png\" alt=\"New Project Structure - Migrations from different project\" width=\"364\" height=\"445\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/New-Project-Structure.png 364w, https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/New-Project-Structure-245x300.png 245w\" sizes=\"auto, (max-width: 364px) 100vw, 364px\" \/><\/a><\/p>\n<p>As soon as we do that, we need to change the namespace in the <code>ApplicationContext<\/code> and <code>Student<\/code> classes from <code>EFCoreApp.Entities<\/code> to just <code>Entities<\/code>. Furthermore, we have to do the same thing for the using directives in the <code>Startup<\/code> class and in <strong>all three migration files<\/strong>.<\/p>\n<p>Having done all that, our project should build successfully.<\/p>\n<h3>Adding a New Migration<\/h3>\n<p>Now we can try to add another migration by typing:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">PM&gt; Add-Migration TestMigrationFromSeparateProject<\/code><\/p>\n<p>But, as soon as we hit the Enter key, we are going to get an error message which explains that our EFCoreApp project doesn\u2019t match our migrations assembly Entities. This error message is great because it provides us with an explanation of how to solve our problem.<\/p>\n<p>All we have to do is to change our migrations assembly, so let\u2019s do exactly that in the <code>Startup<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"5\">public void ConfigureServices(IServiceCollection services)\r\n{\r\n    services.AddDbContext&lt;ApplicationContext&gt;(opts =&gt;\r\n        opts.UseSqlServer(Configuration.GetConnectionString(\"sqlConnection\"),\r\n            options =&gt; options.MigrationsAssembly(\"EFCoreApp\")));\r\n\r\n    services.AddControllers();\r\n}\r\n<\/pre>\n<p><strong>For .NET 6 and above, we have to modify the Program class and use a slightly different code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">builder.Services.AddDbContext&lt;ApplicationContext&gt;(opts =&gt;\r\n        opts.UseSqlServer(Configuration.GetConnectionString(\"sqlConnection\"),\r\n            options =&gt; options.MigrationsAssembly(\"EFCoreApp\")));\r\n    \r\nbuilder.Services.AddControllers();<\/pre>\n<p>Now, we can run the same command again, but this time it will execute successfully. We have successfully created our new migration along with the migration files in the <code>Migrations<\/code> folder:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/12-Test-migration-executed.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-48607\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/12-Test-migration-executed.png\" alt=\"Test Migrations folder\" width=\"439\" height=\"110\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/12-Test-migration-executed.png 439w, https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/12-Test-migration-executed-300x75.png 300w\" sizes=\"auto, (max-width: 439px) 100vw, 439px\" \/><\/a><\/p>\n<p>We can see that the <code>TestMigration<\/code> file has no code in the <code>Up()<\/code> and <code>Down()<\/code> methods, and this is normal because we didn\u2019t change anything, but we completed our required task.<\/p>\n<h2 id=\"removingmigration\">Removing a Migration<\/h2>\n<p>We\u2019ve learned how to create migrations from a separate project. But as a result of that, we have created an empty migration that does nothing in our database.\u00a0 When we create a migration that we\u2019re not satisfied with, we can easily remove it by typing the <code>Remove-Migration [options]<\/code>command in the PMC window. So, let\u2019s do that:<\/p>\n<p><code>PM&gt; Remove-Migration<\/code><\/p>\n<p>After a few seconds our previous migration will be removed:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/13-Removing-previous-migration.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-48608\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/13-Removing-previous-migration.png\" alt=\"Removing migration\" width=\"491\" height=\"60\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/13-Removing-previous-migration.png 491w, https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/13-Removing-previous-migration-300x37.png 300w\" sizes=\"auto, (max-width: 491px) 100vw, 491px\" \/><\/a><\/p>\n<p>Excellent, now we can move on.<\/p>\n<h2 id=\"seeddata\">Seed Data in Entity Framework Core<\/h2>\n<p>In most of our projects, we want to have some initial data in the created database. 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.<\/p>\n<p>We can create the code for the seeding action in the <code>OnModelCreating<\/code> method by using the <code>ModelBuilder<\/code>, as we did for the Fluent API configuration. So, let\u2019s add a few rows into the <code>Student<\/code> table:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"12-26\">protected override void OnModelCreating(ModelBuilder modelBuilder)\r\n{\r\n    modelBuilder.Entity&lt;Student&gt;()\r\n        .ToTable(\"Student\");\r\n    modelBuilder.Entity&lt;Student&gt;()\r\n        .Property(s =&gt; s.Age)\r\n        .IsRequired(false);\r\n    modelBuilder.Entity&lt;Student&gt;()\r\n        .Property(s =&gt; s.IsRegularStudent)\r\n        .HasDefaultValue(true);\r\n\r\n    modelBuilder.Entity&lt;Student&gt;()\r\n        .HasData(\r\n            new Student\r\n            {\r\n                Id = Guid.NewGuid(),\r\n                Name = \"John Doe\",\r\n                Age = 30\r\n            },\r\n            new Student\r\n            {\r\n                Id = Guid.NewGuid(),\r\n                Name = \"Jane Doe\",\r\n                Age = 25\r\n            }\r\n        );\r\n}\r\n<\/pre>\n<p>So, we are using the <code>HasData<\/code> method to inform EF Core about the data it has to seed. The rest of the code is self-explanatory because we are just adding the required data. We are not using the <code>IsRegularStudent<\/code> property because we created a configuration for that property to have a default value.<\/p>\n<p>Now we can create a new migration:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">PM&gt; Add-Migration SeedInitialData<\/code><\/p>\n<p>And apply it:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">PM&gt; Update-Database<\/code><\/p>\n<p>We can check out our table to inspect the result:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/14-Data-seed.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-48610\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/14-Data-seed.png\" alt=\"Data seed\" width=\"507\" height=\"309\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/14-Data-seed.png 507w, https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/14-Data-seed-300x183.png 300w\" sizes=\"auto, (max-width: 507px) 100vw, 507px\" \/><\/a><\/p>\n<h2 id=\"betterwayapplyingconfiguration\">A Better Way for Applying Configuration and Data Seed<\/h2>\n<p>We can place all of the configuration code inside the <code>OnModelCreating<\/code> method, and that will work as it supposed to. As we can see, our <code>OnModelCreating<\/code> method is readable and easy to maintain. But, what if we had a larger project with more classes and more data to seed? Our method would become hard to read and maintain.<\/p>\n<p>EF Core provides a better way for creating a Fluent API configuration by using the <code>IEntityTypeConfiguration&lt;T&gt;<\/code> interface. By using it, we can divide the configuration for each entity into its own separate configuration class.<\/p>\n<p>So, let\u2019s see how to do that.<\/p>\n<p>In the <code>Entities<\/code> project, we are going to create a new folder <code>Configuration<\/code> and inside a new class <code>StudentConfiguration<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class StudentConfiguration : IEntityTypeConfiguration&lt;Student&gt;\r\n{\r\n    public void Configure(EntityTypeBuilder&lt;Student&gt; builder)\r\n    {\r\n        throw new NotImplementedException();\r\n    }\r\n}\r\n<\/pre>\n<p>Of course, we don\u2019t want to throw an exception (it is a default code after VS implements an interface), so, let\u2019s modify this method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public void Configure(EntityTypeBuilder&lt;Student&gt; builder)\r\n{\r\n    builder.ToTable(\"Student\");\r\n    builder.Property(s =&gt; s.Age)\r\n        .IsRequired(false);\r\n    builder.Property(s =&gt; s.IsRegularStudent)\r\n        .HasDefaultValue(true);\r\n\r\n    builder.HasData\r\n    (\r\n        new Student\r\n        {\r\n            Id = Guid.NewGuid(),\r\n            Name = \"John Doe\",\r\n            Age = 30\r\n        },\r\n        new Student\r\n        {\r\n            Id = Guid.NewGuid(),\r\n            Name = \"Jane Doe\",\r\n            Age = 25\r\n        },\r\n        new Student\r\n        {\r\n            Id = Guid.NewGuid(),\r\n            Name = \"Mike Miles\",\r\n            Age = 28\r\n        }\r\n    );\r\n}\r\n<\/pre>\n<p>This code is a little bit different from the old <code>OnModelCreating<\/code> code because we don\u2019t have to use<code> .Entity&lt;Student&gt;<\/code> part anymore. That\u2019s because our builder object is already of type <code>EntityTypeBuilder&lt;Student&gt;<\/code>. We have added an additional object to insert, just to have something to create a migration for.<\/p>\n<p>All we have to do is to modify the <code>OnModelCreating<\/code> method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">protected override void OnModelCreating(ModelBuilder modelBuilder)\r\n{\r\n    modelBuilder.ApplyConfiguration(new StudentConfiguration());\r\n}\r\n<\/pre>\n<p>And that is all.<\/p>\n<p>We can now add a new migration and apply it:<\/p>\n<p><code>PM&gt; Add-Migration AdditionalRowInserted<\/code><\/p>\n<p><code>PM&gt; Update-Database<\/code><\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/15-Additional-row-migration.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-48611\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/15-Additional-row-migration.png\" alt=\"Additional row inserted\" width=\"475\" height=\"117\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/15-Additional-row-migration.png 475w, https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/15-Additional-row-migration-300x74.png 300w\" sizes=\"auto, (max-width: 475px) 100vw, 475px\" \/><\/a><\/p>\n<h2 id=\"setupinitialmigration\">Setup the Initial Migration as Soon as Applications Starts<\/h2>\n<p>For every created migration, we had to apply its changes manually. And this is quite okay. But when we deploy our application, it would be nice to have initial data at that moment in the database.<\/p>\n<p>What would be even nicer is that we don\u2019t have to do that manually, but to start all the required migrations and seed all the required data as soon as the application starts.<\/p>\n<p>Of course, besides being useful on deployment, it helps when sharing or developing our application with other people. We would like them to start the app and execute all the migrations before the app configures.<\/p>\n<p>Well, we are going to show you how to do exactly that.<\/p>\n<h3>Creating an Extension Method<\/h3>\n<p>Let\u2019s create a new class <code>MigrationManager<\/code> in the <code>Entities<\/code> project. It is going to be a static class because we are going to create an extension method to start all the migrations at the application\u2019s startup:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static class MigrationManager\r\n{\r\n}\r\n<\/pre>\n<p>Let&#8217;s continue with the .NET 5 explanation first, and then we will explain the implementation for .NET6 and above.<\/p>\n<p>Now, since we are working on top of the <code>Entities<\/code> class library project, we have to install <strong>Microsoft.ASPNetCore.Hosting.Abstractions<\/strong> library (we need this for the IHost type we are going to use in our extension method) and add the <code>MigrateDatabase<\/code> extension method to this class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static class MigrationManager\r\n{\r\n     public static IHost MigrateDatabase(this IHost host)\r\n     {\r\n         using (var scope = host.Services.CreateScope())\r\n         {\r\n             using (var appContext = scope.ServiceProvider.GetRequiredService&lt;ApplicationContext&gt;())\r\n             {\r\n                 try\r\n                 {\r\n                     appContext.Database.Migrate();\r\n                 }\r\n                 catch (Exception ex)\r\n                 {\r\n                     \/\/Log errors or do anything you think it's needed\r\n                     throw;\r\n                 }\r\n             }\r\n         }\r\n\r\n         return host;\r\n    }\r\n}\r\n<\/pre>\n<p>We are using the <code>IHost<\/code> type because this allows us to chain this method in the <code>Program.cs<\/code> file and of course, as you can see, we need it for the main logic.<\/p>\n<p><strong>In .NET 6 and above, we have a different implementation:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static class MigrationManager\r\n{\r\n    public static WebApplication MigrateDatabase(this WebApplication webApp)\r\n    {\r\n        using (var scope = webApp.Services.CreateScope())\r\n        {\r\n            using (var appContext = scope.ServiceProvider.GetRequiredService&lt;ApplicationContext&gt;())\r\n            {\r\n                try\r\n                {\r\n                    appContext.Database.Migrate();\r\n                }\r\n                catch (Exception ex)\r\n                {\r\n                    \/\/Log errors or do anything you think it's needed\r\n                    throw;\r\n                }\r\n            }\r\n        }\r\n\r\n        return webApp;\r\n    }\r\n}<\/pre>\n<p>So, we are creating a service scope and using it with the <code>ServiceProvider<\/code> to obtain an instance of the <code>ApplicationContext<\/code> class. In <a href=\"https:\/\/code-maze.com\/getting-started-with-efcore\/\" target=\"_blank\" rel=\"noopener noreferrer\">the first article<\/a>, we discussed properties contained in the <code>DbContext<\/code> class, and now, we are using one of them (Database) to call the <code>Migrate<\/code> method for migration execution.<\/p>\n<h3>Applying the MigrateDatabase method<\/h3>\n<p>The next step is to call this method in the <code>Program.cs<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"5\">public static void Main(string[] args)\r\n{\r\n    CreateWebHostBuilder(args)\r\n        .Build()\r\n        .MigrateDatabase()\r\n        .Run();\r\n}\r\n<\/pre>\n<p><strong>For .NET 6, we have to modify the same class, just a bit differently:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"1\">app.MigrateDatabase();\r\napp.Run();<\/pre>\n<p>Finally let\u2019s remove the Student and _EFMigrationsHistory tables from the database and remove the stored procedure in the Programmability folder, to simulate an empty database (or just drop your database). Then, we can start our application. We are going to see logs in a console window stating that migrations are executing. After the migrations have finished their work, we can check the database to confirm that all the tables and a procedure have been created again.<\/p>\n<h2 id=\"revertingandscriptingmigrations\">Reverting and Scripting Migrations<\/h2>\n<p>In one of the previous sections, we learned how to remove migration if we haven\u2019t applied it. But in the case we have, we can\u2019t remove it just like that, we need to revert it to the specific migration.<\/p>\n<p>So, to show how migration reverting works, we are going to add another row in the <code>StudentConfiguration<\/code> class, create, apply migration and then revert it back to the previous values.<\/p>\n<p>Let\u2019s first add another row to seed:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">new Student\r\n{\r\n    Id = Guid.NewGuid(),\r\n    Name = \"TEST Name\",\r\n    Age = 100\r\n}\r\n<\/pre>\n<p>Then let\u2019s create:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">PM&gt; Add-Migration RevertTestMigration<\/code><\/p>\n<p>and apply migration:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">PM&gt; Update-Database<\/code><\/p>\n<p>We can see in the database that a new row has been added. But as we are not satisfied with this migration (hypothetically), let\u2019s revert it:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">PM&gt; Update-Database AdditionalRowInserted<\/code><\/p>\n<p>The <code>AdditionalRowInserted<\/code> migration was the previous one, and if we check our database now, we are going to see that it was reverted to the specific migration values.<\/p>\n<p>Finally, if we want to make a SQL script of all our migrations, we can do that by typing:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">PM&gt; Script-Migration<\/code><\/p>\n<p>This command will create a script file for us.<\/p>\n<h2 id=\"conclusion\">Conclusion<\/h2>\n<p>Excellent, we have learned a lot of different information about data migration and how to use it in various situations within EF Core.<\/p>\n<p>So, to summarize, we have covered:<\/p>\n<ul>\n<li>How to create and apply migrations<\/li>\n<li>The way to add custom code in our migrations<\/li>\n<li>Using model and context classes from a different project for our migrations<\/li>\n<li>How to seed data and set up an initial seed as soon as the project starts<\/li>\n<li>The way to remove, revert migrations, and create script files<\/li>\n<\/ul>\n<p>In<a href=\"https:\/\/code-maze.com\/efcore-relationships\/\" target=\"_blank\" rel=\"noopener noreferrer\"> the next article<\/a>, we are going to learn more about the configuration of relationships in EF core.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this section, we are going to cover Migrations and Seed data features in Entity Framework Core. In the previous parts of this series, we have created the database model (entity and context classes) and applied different configuration options. Now it is time to transfer this database model to the real database in the SQL [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":54835,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[12],"tags":[79,343,53,559,557,558],"class_list":["post-48600","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-csharp","tag-asp-net-core","tag-ef-core","tag-entity-framework-core","tag-initial-migration","tag-migrations","tag-seed-data","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Migrations and Seed Data With Entity Framework Core - Code Maze<\/title>\n<meta name=\"description\" content=\"We are going to learn about Migrations and Seed data in Entity Framework Core and how to optimize EF Core migrations.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Migrations and Seed Data With Entity Framework Core - Code Maze\" \/>\n<meta property=\"og:description\" content=\"We are going to learn about Migrations and Seed data in Entity Framework Core and how to optimize EF Core migrations.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2019-08-12T06:02:22+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-05-22T10:45:04+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/03-ef-core-series-migrations-and-seeding-1.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Marinko Spasojevi\u0107\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Marinko Spasojevi\u0107\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"13 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/\"},\"author\":{\"name\":\"Marinko Spasojevi\u0107\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/d6fa06e66820968d19b39fb63cff2533\"},\"headline\":\"Migrations and Seed Data With Entity Framework Core\",\"datePublished\":\"2019-08-12T06:02:22+00:00\",\"dateModified\":\"2024-05-22T10:45:04+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/\"},\"wordCount\":2444,\"commentCount\":43,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/03-ef-core-series-migrations-and-seeding-1.png\",\"keywords\":[\"asp.net core\",\"EF Core\",\"entity framework core\",\"initial migration\",\"migrations\",\"seed data\"],\"articleSection\":[\"C#\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/\",\"url\":\"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/\",\"name\":\"Migrations and Seed Data With Entity Framework Core - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/03-ef-core-series-migrations-and-seeding-1.png\",\"datePublished\":\"2019-08-12T06:02:22+00:00\",\"dateModified\":\"2024-05-22T10:45:04+00:00\",\"description\":\"We are going to learn about Migrations and Seed data in Entity Framework Core and how to optimize EF Core migrations.\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/03-ef-core-series-migrations-and-seeding-1.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/03-ef-core-series-migrations-and-seeding-1.png\",\"width\":1100,\"height\":620,\"caption\":\"03 - ef core series migrations and seeding\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Migrations and Seed Data With Entity Framework Core\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/d6fa06e66820968d19b39fb63cff2533\",\"name\":\"Marinko Spasojevi\u0107\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/marinko-1x1-3-150x150.jpg\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/marinko-1x1-3-150x150.jpg\",\"caption\":\"Marinko Spasojevi\u0107\"},\"description\":\"Hi, my name is Marinko Spasojevic. Currently, I work as a full-time .NET developer and my passion is web application development. Just getting something to work is not enough for me. To make it just how I like it, it must be readable, reusable, and easy to maintain. Prior to being an author on the CodeMaze blog, I had been working as a professor of Computer Science for several years. So, sharing knowledge while working as a full-time developer comes naturally to me.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/in\/marinko-spasojevic\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog\"],\"url\":\"https:\/\/code-maze.com\/author\/marinko\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Migrations and Seed Data With Entity Framework Core - Code Maze","description":"We are going to learn about Migrations and Seed data in Entity Framework Core and how to optimize EF Core migrations.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/","og_locale":"en_US","og_type":"article","og_title":"Migrations and Seed Data With Entity Framework Core - Code Maze","og_description":"We are going to learn about Migrations and Seed data in Entity Framework Core and how to optimize EF Core migrations.","og_url":"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/","og_site_name":"Code Maze","article_published_time":"2019-08-12T06:02:22+00:00","article_modified_time":"2024-05-22T10:45:04+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/03-ef-core-series-migrations-and-seeding-1.png","type":"image\/png"}],"author":"Marinko Spasojevi\u0107","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Marinko Spasojevi\u0107","Est. reading time":"13 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/"},"author":{"name":"Marinko Spasojevi\u0107","@id":"https:\/\/code-maze.com\/#\/schema\/person\/d6fa06e66820968d19b39fb63cff2533"},"headline":"Migrations and Seed Data With Entity Framework Core","datePublished":"2019-08-12T06:02:22+00:00","dateModified":"2024-05-22T10:45:04+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/"},"wordCount":2444,"commentCount":43,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/03-ef-core-series-migrations-and-seeding-1.png","keywords":["asp.net core","EF Core","entity framework core","initial migration","migrations","seed data"],"articleSection":["C#"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/","url":"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/","name":"Migrations and Seed Data With Entity Framework Core - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/03-ef-core-series-migrations-and-seeding-1.png","datePublished":"2019-08-12T06:02:22+00:00","dateModified":"2024-05-22T10:45:04+00:00","description":"We are going to learn about Migrations and Seed data in Entity Framework Core and how to optimize EF Core migrations.","breadcrumb":{"@id":"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/03-ef-core-series-migrations-and-seeding-1.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2019\/08\/03-ef-core-series-migrations-and-seeding-1.png","width":1100,"height":620,"caption":"03 - ef core series migrations and seeding"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"Migrations and Seed Data With Entity Framework Core"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/d6fa06e66820968d19b39fb63cff2533","name":"Marinko Spasojevi\u0107","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/marinko-1x1-3-150x150.jpg","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/marinko-1x1-3-150x150.jpg","caption":"Marinko Spasojevi\u0107"},"description":"Hi, my name is Marinko Spasojevic. Currently, I work as a full-time .NET developer and my passion is web application development. Just getting something to work is not enough for me. To make it just how I like it, it must be readable, reusable, and easy to maintain. Prior to being an author on the CodeMaze blog, I had been working as a professor of Computer Science for several years. So, sharing knowledge while working as a full-time developer comes naturally to me.","sameAs":["https:\/\/www.linkedin.com\/in\/marinko-spasojevic\/","https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog"],"url":"https:\/\/code-maze.com\/author\/marinko\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/48600","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=48600"}],"version-history":[{"count":8,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/48600\/revisions"}],"predecessor-version":[{"id":63342,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/48600\/revisions\/63342"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/54835"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=48600"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=48600"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=48600"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}