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) {

    base.OnModelCreating(modelBuilder);

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

    modelBuilder.ApplyConfigurationsFromAssembly(typeof(DatabaseContext).Assembly);

    var model = modelBuilder.Model;

//possibly filter entities by some criteria?

    foreach (var entity in model.GetEntityTypes())

    {

        entity.RemoveAnnotation(“Relational:Schema”);

        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.

Published by

Ricardo Peres

Tech Lead at RedLight Software.

Leave a Reply

Your email address will not be published. Required fields are marked *