3

I have this code on my OnModelCreating method:

// Users
modelBuilder.Entity<User>().ToTable(name: "Users", schema: "Core");
modelBuilder.Entity<User>().HasKey(x => x.Id);

// Seeder
modelBuilder.Entity<User>().HasData(MigrationSeeder.Seed());

When I generate migration, EF create insert operation like this:

migrationBuilder.InsertData(
    schema: "Core",
    table: "Users",
    columns: new[] { "Id", "FirstName", "LastName" },
    values: new object[] { "6c6aa94903a4", "Rick", "Sánchez" });

All right!

But.. when I generate another migration, EF repeat this insert operation (before deleting rows and after, inserting the new rows)

migrationBuilder.DeleteData(
    schema: "Core",
    table: "Users",
    keyColumn: "Id",
    keyValue: "6c6aa94903a4");

migrationBuilder.InsertData(
    schema: "Core",
    table: "Users",
    columns: new[] { "Id", "FirstName", "LastName" },
    values: new object[] { "d055353aa45c", "Rick", "Sánchez" });

If this entities corresponding with master tables and database has related rows in another tables.

How can avoid insert in every migration?

Sergio
  • 175
  • 5
  • 21
  • See [my answer](https://stackoverflow.com/a/45942026/455493) here on how to properly seed in EF Core >= 2.0 (the pattern was changed slightly from 1.x) – Tseng Jun 14 '18 at 13:55
  • 1
    @Tseng Thanks! but your post does not reflect how migrations work in 2.1 – Sergio Jun 14 '18 at 14:25
  • Where does your id come from? Is it a random generated in your code? Since the ID from the first and 2nd migration are different – Tseng Jun 14 '18 at 14:45
  • @Tseng Yes, the ID generation is random (through Guid) – Sergio Jun 15 '18 at 07:00
  • 1
    But how do you expect the tools to generate correct migration files, when the id changes every time when you create the migration?! You should try using fixed ids in your seed method (or no id at all, if there is another unique field, such as user name or firstname/last name combination) or "username"/email – Tseng Jun 15 '18 at 07:02

0 Answers0