37

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; }
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
John S
  • 7,909
  • 21
  • 77
  • 145

2 Answers2

61

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.

DfrDkn
  • 1,270
  • 2
  • 16
  • 23
  • 2
    When I tried to set "HasDefaultSchema", I get this error - the model backing the '' context has changed since the database was created. Consider using Code First Migrations to update the database. Do you know how to resolve it or what is the cause? – superachu Oct 13 '16 at 14:21
  • @AchuthaKrishnan to solve that you need to update your migrations. This is a good [tutorial](http://www.learnentityframeworkcore.com/migrations). In cmd prompt, run this: dotnet ef database update – Fabio Jun 28 '17 at 20:33
  • this is not working even EF6. whenever i instantiate the context , OnModelCreating function is not calling , any idea? – AhammadaliPK Sep 25 '19 at 10:18
  • still hitting the default public schema – Morgeth888 Nov 04 '21 at 14:40
  • 1
    ohhh ok, big detail here, your migrations will not be reran, its on creating them the default schema matters. – Morgeth888 Nov 04 '21 at 14:51
12

According to official Microsoft documentations, you should use either Data annotations or FluentAPI.

  1. For DataAnnotations:
[Table("blogs", Schema = "blogging")]
public class Blog
{

    public int BlogId { get; set; }
    public string Url { get; set; }
}
  1. 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

Grzegorz Smulko
  • 2,525
  • 1
  • 29
  • 42
Onaefe
  • 306
  • 2
  • 4