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);
});
}
}
partial
. Wich method should be executed first, or how should the compiler know, how to merge partial methods? From microsoft docs:A partial method declaration consists of two parts: the definition, and the implementation.
1/2 – Reprographypartial
from your method declaration and put your logic in one of your classes. 2/2 – ReprographyOnModelCreatingPartial
solution, so the accepted answer helped me a lot. I believe it deserves to be the accepted answer inspite of Simon's answer is best workaround for nowadays. – Danelaw