Entity framework - How to add static data using data seeding

I am not sure that the correct term is "static" data - it seems to be known as seeding, which is the term I will use. Sometimes you add tables in your database with "types", these are somewhat similar to enums you would find in code. For this type of data you can use the HasData method when building your entity model. This will make the seeded data part of your migration and will be applied together with your model.

If we have the following entity:

public class MyEntity {
    public int Id { get; set; }
    public string Text { get; set; }
    public string Type { get; set; }
}

Then we can seed some value using HasData:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<MyEntity>(e =>
    {
        e.HasKey(c => new { c.Id });
        e.HasData(new { Id = 1, Text = "This is a text", Type = "This is the type" });
    });
}

When running your migration (dotnet ef migrations add addMyEntityData) you will see the following Up migration added:

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.InsertData(
        table: "MyEntities",
        columns: new[] { "Id", "Text", "Type" },
        values: new object[] { 1, "This is a text", "This is the type" });
}

You can see that it will add the strings from the model to the table when migrating.

That is all there is to it, let me know what you think in the comments down below! :)