Search code examples
c#entity-frameworkmigrationdbcontextseeding

Is there any way to seed data on entity framework migration. but we don't need to provide primary key value on seeding


model class:

  public class Model
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
    }

dbContext Class

    public class AppDbContext : DbContext
    {
        public AppDbContext (DbContextOptions<AppDbContext> options)
            : base(options)
        {        
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Model>().HasData(
                new Model {Name = "William"},
                new Model { Name="Altaf"}
            );
        }
        public DbSet<DataSeedingEntityFramework.Model> Model { get; set; }
    }

this error show when i migrate dbcontext:

The seed entity for entity type 'Model' cannot be added because a non-zero value is required for property 'Id'. Consider providing a negative value to avoid collisions with non-seed data.

i know why this error show but i want to migrate without Id value. It should be auto increment.


Solution

  • You should add

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    

    This will tell EF Core that the entity has autoincrement field ID. To enable data seed on migration move code from OnModelCreating method in DbContext class to Up method in your migration class. See this page for more details.