In this post, we’re going to see another very important element within the Code First approach: data import, or data seed in English.
Table of Contents
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:
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.
If there is any problem you can add a comment bellow or contact me in the website's contact form