Changing Schema Dynamically in EF Core

Sometimes it may be necessary to change the schema for some entities based upon some criteria. This may be because of multitenancy or because you want to test something and don’t want to pollute the main schema. Here is a possible solution, going directly to the annotations that EF Core uses.

protected override void OnModelCreating(ModelBuilder modelBuilder) {


//apply any IEntityTypeConfiguration<TEntity> configuration from this assembly


    var model = modelBuilder.Model;

//possibly filter entities by some criteria?

    foreach (var entity in model.GetEntityTypes())



        entity.AddAnnotation("Relational:Schema", "FooBar");

    } }

You need to override the OnModelCreating method, which is called by the infractructure when the model is being built by EF Core, and you let it do its job, and you then iterate through the found entities to add an annotation for “Relational:Schema”. And that’s it.


No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website