I want to seed some data using EntityFramework in .net core 3.1 and I'm facing an issue:
I've got two SQL tables (so two DbSet<>):
public virtual DbSet<TableA> TableA { get; set; }
public virtual DbSet<TableB> TableB { get; set; }
Table A has this structure:
[Key]
public int Id { get; set; } // PK
public string EnglishText { get; set; } // some value
Table B has this structure:
[Key]
public int Id { get; set; } // PK
public int TableAId { get; set; } // FK to Table A
public string TranslatedText { get; set; } // some value
For seeding the data for table A, I use the OnModelCreating(ModelBuilder modelBuilder) method in the DBContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Seed TableA
modelBuilder.Entity<TableA>().HasData(
new TableA { Id = 1, EnglishText = "first data"}
);
}
I then want to seed table B only if it doesn't contain a record that reference TableA (via the FK), I'm not sure how to do that in the OnModelCreating method.
I guess I'm after something like:
modelBuilder.Entity<TableB>().HasData(var X = new TableB{...}).Where([X.TableAId is not in TableA])
If someone has an idea or can point me in a direction, that would be very much appreciated.