Skip to content

Partial Adding extra model entites to generated DbContext

Simon Hughes edited this page Aug 23, 2022 · 4 revisions

It's easy to add other manually created models/entities to your Reverse POCO-generated DbContext.

Download an example solution: MixOfReversePocoAndManualEntities.zip

Some entities are generated, and some are manually written. All entities end up in the same database context, allowing Reverse POCO to overwrite its database context without losing any changes in your partial database context, which extends it with your own entities.

How to do it:

In your <database>.tt file, set

Settings.DbContextClassModifiers     = "public partial";
Settings.DbContextInterfaceModifiers = "public partial";

The above will generate a database context like:

// Generated database context interface
public partial interface IMyDbContext : IDisposable
{
    ...
}

// Generated db context
public partial class MyDbContext : DbContext, IMyDbContext
{
    public MyDbContext()
    {
        InitializePartial(); // <-- See here
    }

    public MyDbContext(DbContextOptions<MyDbContext> options)
        : base(options)
    {
        InitializePartial(); // <-- See here
    }

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

        modelBuilder.ApplyConfiguration(new SomeGeneratedEntity());
        ...

        OnModelCreatingPartial(modelBuilder); // <-- See here
    }

    // See here
    partial void InitializePartial();
    partial void DisposePartial(bool disposing);
    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);

Having partial will allow you to add more functionality to your MyDbContext class and your interface class IMyDbContext in a separate file. Such as:

public partial interface IMyDbContext
{
    // Add your entities here
    DbSet<MyManuallyCreatedEntity> MyEntities { get; set; }
}

public partial class MyDbContext
{
    // Add your entities here
    public DbSet<MyManuallyCreatedEntity> MyEntities { get; set; }

    partial void InitializePartial()
    {
        // Optional. Any initialisation during constructor can be done here.
    }

    partial void OnModelCreatingPartial(ModelBuilder modelBuilder)
    {
        // Add your configuration classes here
        modelBuilder.ApplyConfiguration(new MyManuallyCreatedEntityConfiguration());
    }

    partial void DisposePartial(bool disposing)
    {
        // optional
    }
}