Entity Framework Core Seed
▌Introduction
This article shows how to seed (initialize data) with Entity
framework core and some key points.
▌Environment
▋ASP.NET Core 2.2.101
▋EF Core 2.2.4
▌Implement
▋Create
ModelBuilderExtensions
In the Data Access project,
create the ModelBuilderExtensions and use EntityTypeBuilder<TEntity>.HasData(TEntity[])
to have seed data as following,
▋ModelBuilderExtensions.cs
public static class
ModelBuilderExtensions
{
public static void Seed(this ModelBuilder
modelBuilder)
{
modelBuilder.Entity<SupportedLanguage>()
.HasData(
new MapLang {
Id = 1,
Name = "繁體中文",
NameEn = "Traditional
Chinese",
NameCn = "繁體中文" },
new MapLang {
Id = 2,
Name = "简体中文",
NameEn = "Simplified
Chinese",
NameCn = "简体中文" },
new MapLang {
Id = 3,
Name = "英文",
NameEn = "English",
NameCn = "英文" });
}
}
Notice that even if the
Primary key (For example: “Id”) is an Identity/Sequence column and has DataAnnotation,
[DatabaseGenerated(DatabaseGeneratedOption.Identity)],
to make sure that the seed data is in database, EF core needs the specified value of the Identity/Sequence column when
seeding data.
When the HasData method is used, EF Core
automatically generates SET
IDENTITY INSERT ON for the relevant table, and the set it to OFF once the seeding has
completed.
So that will make the table’s Sequence not updated.
|
For example, the latest
sequence of table, SupportedLanguages, is still be 1 after
seeding data.
So we have to manually update/reset the Sequence.
1. Generate
migration files by
dotnet ef migrations add <migration_name>
2. Update the migration
Find the migration file, such as 20190603123102_InitCreate.cs. Write down the update/reset Sequence sql in the end of the Up function.
Find the migration file, such as 20190603123102_InitCreate.cs. Write down the update/reset Sequence sql in the end of the Up function.
public partial class InitCreate : Migration
{
protected override void Up(MigrationBuilder
migrationBuilder)
{
//...
// Sql
server
migrationBuilder.Sql(@"
ALTER SEQUENCE SupportedLanguages RESTART WITH 4;");
// Postgres
migrationBuilder.Sql(@"
ALTER SEQUENCE
""SupportedLanguages_Id_seq"" RESTART WITH 4;");
}
}
Then the Sequence will keep the right latest number after updating the
migration.
▌Reference
沒有留言:
張貼留言