-
Notifications
You must be signed in to change notification settings - Fork 226
Partial Adding extra model entites to generated DbContext
Simon Hughes edited this page Aug 14, 2022
·
4 revisions
It's easy to add additional manually created models/entities to your Reverse POCO generated DbContext. In your <database>.tt file, set
Settings.DbContextClassModifiers = "public partial";
Settings.DbContextInterfaceModifiers = "public partial";This will generate a db context like:
// Generated db 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);This will allow you to add more functionality to your MyDbContext class and your interface class IMyDbContext in a separate file that is not generated:
public partial interface IMyDbContext
{
DbSet<MyManuallyCreatedEntity> MyEntities { get; set; }
}
public partial class MyDbContext
{
public DbSet<MyManuallyCreatedEntity> MyEntities { get; set; }
partial void InitializePartial()
{
// Any initialisation during constructor can be done here
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new MyManuallyCreatedEntityConfiguration());
}
partial void DisposePartial(bool disposing)
{
// optional
}
}- Home
- Compared with the Microsoft scaffolder
- Connection strings
- JetBrains Rider
- Upgrading from v3 to v4
- Saving .tt does nothing
- Settings A-Z - every setting, with a page each
- Common Settings Types Explained
- Settings Callbacks
- Settings runtime values and helpers
- Filtering
- Full Control Over the Generated Code
- Enum Generation from Table Data
- Owned Entities
- JSON column support
- Global Query Filters
- Extended Property Names Feature
- Partial Properties
- File-Scoped Namespaces
- Data Annotations
- Spatial Types
- HierarchyId
- RowVersion and TimeStamp columns
- Lazy Loading
- Stored proc result sets