Home > database >  Seeding Entity Framework Core 6 .NET6 not working
Seeding Entity Framework Core 6 .NET6 not working

Time:02-04

I created my Entity Framework Context like this

public class ProductContext : DbContext
{
    public ProductContext(DbContextOptions<ProductContext> options) : base(options) { }
    public DbSet<Product> Products { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //
        modelBuilder.ApplyConfiguration(new ProductEntityTypeConfiguration());

        // seeding
        modelBuilder.Entity<Product>().HasData(
            new Product() { Id = 1, Name = "cola",  Price = new Money(Currency.EUR, 100) },
            new Product() { Id = 2, Name = "chips", Price = new Money(Currency.EUR, 150) },
            new Product() { Id = 3, Name = "candy", Price = new Money(Currency.EUR, 200) }
        );
        base.OnModelCreating(modelBuilder);
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseInMemoryDatabase(databaseName: "ProductDatabase");
        base.OnConfiguring(optionsBuilder);
    }
}


public class ProductEntityTypeConfiguration : IEntityTypeConfiguration<Product>
{
    public void Configure(EntityTypeBuilder<Product> builder)
    {
        builder.ToTable("Product");

        builder.HasKey(product => product.Id);

        builder.Property(product => product.Name)
               .HasColumnName("Name");

        builder.Property(product => product.Price)
               .HasConversion(
                   v => JsonConvert.SerializeObject(v, Formatting.Indented),
                   v => JsonConvert.DeserializeObject<Money>(v));
    }
}

And I declare it in my Program.cs

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<ProductContext>();

I don't understand why but everything compiles and runs without errors. But Data in database is not seeded. I can add records , remove them and work with the database but initial seed setup seems not to be loaded. What I'm doing wrong ?

CodePudding user response:

Provided a tutorial for Seeding Data in Entity Framework Core, refer to Seed Data in Entity Framework Core section, you need to:

  1. Add-Migration for creating seeding data migration.
PM> Add-Migration SeedInitialData
  1. Run Update-Database command to apply newly created migration to the database.
PM> Update-Database
  •  Tags:  
  • Related