By default when you are using Entity Framework code first, the default ‘dbo’ schema is used. But what if you want to use a different schema?
There are multiple ways to do this.
Option 1: Use the ModelBuilder API
One way to change the schema is by using the modelbuilder API. To use this override the OnModelCreating option on your db and specify a schemaName using the Fluent API:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protected override void OnModelCreating(DbModelBuilder modelBuilder) | |
{ | |
modelBuilder.Entity<Customer>().ToTable("Customers", schemaName: "CustomSchemaName"); | |
} |
Option 2: Use attributes
Another option is the usage of Attributes on your model classes:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Table("Customers", Schema = "CustomSchemaName")] | |
public class Customer | |
{ | |
... | |
} |