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 the 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);
}
}