Menu

Entity Framework Core setting default database schema

Unless you set your default database schema in Entity Framework every thing will be created on the dbo. Since cloud hosting is expensive we are having one database for all our apps a but different schemas. You can do this schema like below.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.RemovePluralizingTableNameConvention();
   modelBuilder.HasDefaultSchema("MyProject");
}

Nice, if you are using CodeFirst now it create all the table in given schema, but you will notice that MigrationHistory table still in the dbo, that is alright as we do not have issue on migration with Entity Framework Core. But still I prefer to have project specific MigrationHistory table. you can do this by creating your own configuration like below.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
  base.OnConfiguring(optionsBuilder);
  ConfiguringUpdateMigrationsHistoryTable(optionsBuilder);
}

private static void ConfiguringUpdateMigrationsHistoryTable(DbContextOptionsBuilder optionsBuilder)
{
  var relationalOptions = RelationalOptionsExtension.Extract(optionsBuilder.Options);
  relationalOptions.MigrationsHistoryTableName = "__MigrationHistory";
  relationalOptions.MigrationsHistoryTableSchema = "MyProject";
}

Leave a comment