How to extend DbContext with partial class and partial OnModelCreating method in EntityFramework Core

EFCore 3 – They FINALLY fixed this!

You can now implement OnModelCreatingPartial in a partial class like this. Note the partial keyword on both the class and method:

public partial class RRStoreContext : DbContext
{
    partial void OnModelCreatingPartial(ModelBuilder builder)
    {
        builder.Entity<RepeatOrderSummaryView>().HasNoKey();
    }
}

If you look at the generated context file – right at the very end of OnModelCreating(...) you’ll see…

 OnModelCreatingPartial(modelBuilder);

Note: I use scaffolding, but I needed to manually add HasNoKey for a stored procedure (with a custom return type that wasn’t otherwise scaffolded).

Leave a Comment