Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; } } 
like image 841
John S Avatar asked May 28 '15 16:05

John S


People also ask

How do I set schema name in Entity Framework?

As with any code-first schema customization, you can do this by using the entity classes' attributes or through the DbModelBuilder API. With data annotations, you can use the optional second parameter of the Table attribute to specify the schema name. The code in Figure 3 implements this change in the model.

How do I change the schema name at runtime in Entity Framework?

First step is to create a partial class that allows you to pass a value to the constructor of your entities, by default it uses the values from your config file. Next create the function that will modify your store schema . ssdl file in memory.

What is the easiest approach to assign a default schema for all of the tables used by a DbContext?

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.


1 Answers

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.

like image 151
DfrDkn Avatar answered Oct 12 '22 12:10

DfrDkn