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

Viewed 26304

I'm using EF Core and DatabaseFirst approach. My dbContext is created automatically by Scaffold-DbContext command.

I need to add some new DbSets into a dbContext and add into OnModelCreating method some additional code but after each scaffolding that added code are erased and I have to add it each time again.

What I want to do is to create another partial dbContext class and mark protected override void OnModelCreating(ModelBuilder modelBuilder) method as partial

but get errors:

A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers.

A partial method may not have multiple implementing declarations

Here is a pseudo code:

MyDbContext1.cs - generated by Scaffold-DbContext

public partial class MyDbContext : DbContext
{
    public MyDbContext()
    {
    }

    public MyDbContext(DbContextOptions<MyDbContext> options)
        : base(options)
    {
    }

    public virtual DbSet<Client> Clients { get; set; }

    protected override partial void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Client>(entity =>
        {
            // some code ...
        }
    }
}

MyDbContext2.cs - this code I added each time into dbContext after scaffolding:

public partial class MyDbContext
{
    public virtual DbSet<JustAnotherEntity> AnotherEntity { get; set; }

    protected override partial void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<JustAnotherEntity>(entity =>
        {
            entity.HasKey(e => new {e.Id, e.IdAction, e.IdState})
                .ForSqlServerIsClustered(false);
        });
    }
}
5 Answers

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

An alternative would be creating another context class that inherit from MyDbContext that actually include all the custom code. and then use this new class as your context. This way, there is no need to update the generated code.

public class MyDbContext2 : MyDbContext 
{
    public MyDbContext2()
    {
    }

    public MyDbContext2(DbContextOptions<MyDbContext> options)
        : base(options)
    {
    }

    public virtual DbSet<JustAnotherEntity> AnotherEntity { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<JustAnotherEntity>(entity =>
        {
            entity.HasKey(e => new {e.Id, e.IdAction, e.IdState})
                .ForSqlServerIsClustered(false);
        });
    }
}

You can't override methods in a partial class because all of the "parts" become a single class. But you can accomplish this by having the main OnModelCreating call a partial method. Like this:

public partial class Db : DbContext
{
    partial void OnModelCreating2(ModelBuilder modelBuilder)
    {
       //additional config
    }
}

public partial class Db : DbContext
{

    public DbSet<Person> Persons { get; set; }

    partial void OnModelCreating2(ModelBuilder modelBuilder);
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        OnModelCreating2(modelBuilder);
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=localhost;database=efcore2test;integrated security=true");
        base.OnConfiguring(optionsBuilder);
    }
}

The purpose of partial classes is that you can create another partial class with same name. You can leverage the partial class benefit here.

Create another class with same name as "MyDbContext" but set the file name different e.g. "MyCustomDbContext".

public partial class MyDbContext
{
    partial void OnModelCreatingPartial(ModelBuilder modelBuilder){
        // Right your custom code here
    }
}

Now whenever you will generate the models again, it won't rewrite your custom context class.

It is possible to use partial methods in the manner below:

public partial class MyDbContext : DbContext
{
    public MyDbContext()
    {
    }

    public MyDbContext(DbContextOptions<MyDbContext> options)
        : base(options)
    {
    }

    ...

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        OnModelCreatingPartial(modelBuilder);
    }

    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}

Both EF Core Power Tools and later releases of EF Core (in my case EF Core version 6) generates this setup.

https://marketplace.visualstudio.com/items?itemName=ErikEJ.EFCorePowerTools

https://docs.microsoft.com/en-us/ef/core/get-started/overview/install

Given that the autogenerated DbContext prepare a method not fully implemented you can yourself implement it easily elsewhere in another file:

public partial class MyDbContext : DbContext
{
    partial void OnModelCreatingPartial(ModelBuilder modelBuilder)
    {
        // Your own stuff here!
    }
}

Of course the above require you to have the 'template' for the partial method generated (as both tools above provide). Otherwise you need to be of control of the code and be able to adapt just a few lines of code in the generated class.

More about how partial methods are used:

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/partial-classes-and-methods#partial-methods

Related