'How to conditionaly seed data in EF Core when app is deployed on mutliple pods

I have application that runs on multiple pods. I want to seed some data into the db as a part of migration(to avoid race condition issues). However I need to be able to specify a predicate/conditional statement when to insert the data, I need to first check if a given record exists in it. Like so:

public virtual DbSet<SomeClass> SomeClazz {get;set}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  //...
 
 if(SomeClazz.Find(id).FirstOrDefault != null) //check if a record exists first in the db
 {
  modelBuilder.Entity<Department>()
         .HasData(
           new Department { DepartmentID = 1, Name = "HR" },
           new Department { DepartmentID = 2, Name = "Admin" },
           new Department { DepartmentID = 3, Name = "Development" }
         );
 }
  //...
}

But to the best of my knowledge I shouldn't access the db sets in the OnModelCreating method. How to do it safely then? I want it to be one time execution only thing like migration.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source