I have an entity that has an Auto-identity (int) column. As part of the data-seed I want to use specific identifier values for the \"standard data\" in my syste
For future Googlers, I found the answers suggesting some conditional logic in the OnModelCreating() didn't work for me.
The main issue with this approach is EF caches the model, so it's not possible to switch identity on or off in the same app domain.
The solution we adopted was to create a second derived DbContext which allows identity insert. This way, both models can be cached, and you can use the derived DbContext in the special (and hopefully) rare cases when you need to insert identity values.
Given the following from @RikRak's question:
public class ReferenceThing
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
}
public class MyDbContext : DbContext
{
public DbSet ReferenceThing { get; set; }
}
We added this derived DbContext:
public class MyDbContextWhichAllowsIdentityInsert : MyDbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity()
.Property(x => x.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}
}
Which would then be used with the Seeder as follows:
var specialDbContext = new MyDbContextWhichAllowsIdentityInsert();
Seeder.Seed(specialDbContext);