Changing Default Schema in Entity Framework Code First
A quick tip for Entity Framework Code First when working with SQL Server schemas.
The Problem
There are occasions when you want to create the database in a schema other than the default
dbo schema in SQL Server.
Basic Solution: Simple Tables
For basic entity tables, you can use the following instruction:
modelBuilder.Entity<Settings>().ToTable("Settings", schemaName);
The Many-to-Many Challenge
However, all tables that create many-to-many relationships will still end up in the
dbo schema by default.
To fix this, you need to use a Fluent API trick to make the adjustment.
Solution for Many-to-Many Tables
modelBuilder.Entity<User>()
.HasMany(p => p.groups)
.WithMany(r => r.users)
.Map(m => m.ToTable("UsersByGroups", schemaName));
Where schemaName is a variable
containing the name you want for your schema.
Important Considerations
Side Effects with Inheritance
This approach has some side effects when working with objects that use inheritance hierarchies. However, for most scenarios, it works quite well.
Future Improvements
The Entity Framework team is aware of the need to modify the schema globally and is working on it. This workaround will likely become unnecessary in future versions.
Complete Example
Here's a more complete example showing how to configure multiple entities with a custom schema:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
string schemaName = "MyCustomSchema";
// Configure simple entities
modelBuilder.Entity<Settings>()
.ToTable("Settings", schemaName);
modelBuilder.Entity<User>()
.ToTable("Users", schemaName);
modelBuilder.Entity<Group>()
.ToTable("Groups", schemaName);
// Configure many-to-many relationships
modelBuilder.Entity<User>()
.HasMany(p => p.groups)
.WithMany(r => r.users)
.Map(m => m.ToTable("UsersByGroups", schemaName));
base.OnModelCreating(modelBuilder);
}
Why Use Custom Schemas?
- • Organize tables logically in large databases
- • Separate application concerns at the database level
- • Manage permissions more granularly
- • Support multi-tenant architectures