Setting schema name for DbContext
I know how to set the schema for a table in my context but is there a way to set the default schema for all the tables in a context? i.e.
[Schema = "Ordering"]
public class MyContext:DbContext
{
public MyContext()
: base("name=ConnectionString")
{
}
public DbSet<Student> Students { get; set; }
}
You can configure the default schema in OnModelCreating method of your custom inherited DbContext class like -
public class MyContext: DbContext
{
public MyContext(): base("MyContext")
{
}
public DbSet<Student> Students { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Configure default schema
modelBuilder.HasDefaultSchema("Ordering");
}
}
Starting with EF6 you can use the HasDefaultSchema method on DbModelBuilder to specify the database schema to use for all tables, stored procedures, etc. This default setting will be overridden for any objects that you explicitly configure a different schema for.
According to official Microsoft documentations, you should use either Data annotations or FluentAPI.
- For DataAnnotations:
[Table("blogs", Schema = "blogging")]
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
- For FluentAPI
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.ToTable("blogs", schema: "blogging");
}
or to define the default schema at the model level with the fluent API:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("blogging");
}
Microsoft docs