How to Add Initial Data to a Database with Entity Framework Core

In this post, we’re going to see another very important element within the Code First approach: data import, or data seed in English.

 

 

1 - What is Data seed in entity framework core?

Data seed, or data import, is the capability to import initial data into a database at the start of your application. It’s a very useful practice when you need to preload reference or static data into your system.

A clear example would be currencies with their symbols and codes, since they rarely change; they are a classic example (if you use them, of course) of preloaded data.

 

 

2 - Implementing data seed with Entity Framework core

To implement Data seed, we do this through migrations that we saw in the previous post. If you’re not familiar with migrations, have a look there before continuing.

 

To add the data, we need to do it within the OnModelCreating method inside our DbContext. We know that the dbcontext contains the database configuration, tables, etc., and of course it also contains data migrations.

 

Here we can see an example of how to import a default user:

public class CursoEfContext : DbContext
{
    public virtual DbSet<User> Users { get; set; }

    public virtual DbSet<Wokringexperience> Wokringexperiences { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https: //go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
        => optionsBuilder.UseMySQL("server=127.0.0.1;port=4306;database=cursoEF;user=root;password=cursoEFpass");


    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>().HasData(
            new User { Email = "[email protected]", Id = 1, UserName = "user1" },
            new User { Email = "[email protected]", Id = 2, UserName = "user2" }
        );
    }
}

 

As you can imagine, to avoid letting this method grow infinitely, there are better ways to implement data seeding.

 

Previously, you would simply create a separate class, instantiate and execute it from the method. But starting from .NET Core, there are better options: you can use classes that implement the IEntityTypeConfiguration interface.

 

This interface contains a single method, which we are going to implement, and here’s where we’ll indicate the data seed:

public class UserSeed : IEntityTypeConfiguration<User>
{
    public void Configure(EntityTypeBuilder<User> builder)
    {
        builder.HasData(
            new User { Email = "[email protected]", Id = 1, UserName = "user1" },
            new User { Email = "[email protected]", Id = 2, UserName = "user2" }
        );
    }
}

 Now, we just need to invoke that class, and just like the first version, we do it inside the OnModelCreating method:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyConfiguration(new UserSeed());
}
  • Note: Since version 2.2 you can use modelBuilder.ApplyConfigurationsFromAssembly along with the assembly where you have the interfaces and they will be implemented automatically, but honestly I prefer the “normal” way as it’s clearer (in my opinion).

 

Now we just need to create a migration, as we saw in the previous post. You can see that it creates a file with the corresponding Up and Down methods:

namespace CursoEFCore.Codefirst.API.Migrations
{
    /// <inheritdoc />
    public partial class AddSeedUsers : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.InsertData(
                table: "Users",
                columns: new[] { "Id", "Email", "UserName" },
                values: new object[,]
                {
                    { 1, "[email protected]", "user1" },
                    { 2, "[email protected]", "user2" }
                });
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DeleteData(
                table: "Users",
                keyColumn: "Id",
                keyValue: 1);

            migrationBuilder.DeleteData(
                table: "Users",
                keyColumn: "Id",
                keyValue: 2);
        }
    }
}
  • Note: It also modifies the snapshot.

 

Finally, run the code and you can see how the database is created with the new data in the tables:

data seed execution with EF core

 

Conclusion

In this post, we’ve seen what Data seed or preloading data means in Entity Framework Core.

How to implement Data Seed in Entity Framework Core.

 

This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

Uso del bloqueador de anuncios adblock

Hola!

Primero de todo bienvenido a la web de NetMentor donde podrás aprender programación en C# y .NET desde un nivel de principiante hasta más avanzado.


Yo entiendo que utilices un bloqueador de anuncios como AdBlock, Ublock o el propio navegador Brave. Pero te tengo que pedir por favor que desactives el bloqueador para esta web.


Intento personalmente no poner mucha publicidad, la justa para pagar el servidor y por supuesto que no sea intrusiva; Si pese a ello piensas que es intrusiva siempre me puedes escribir por privado o por Twitter a @NetMentorTW.


Si ya lo has desactivado, por favor recarga la página.


Un saludo y muchas gracias por tu colaboración

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café