Can I change the default schema name in entity framework 4.3 code-first?

前端 未结 5 902
野的像风
野的像风 2020-12-04 17:57

Currently I am deploying my application to a shared hosting environment and code-first with migrations has been working great except for one minor hiccup. Everytime I want t

相关标签:
5条回答
  • 2020-12-04 18:06

    For database first implementations, its easy. Open the edmx file, right click-> Properties and set the default database schema.

    For code first, this article seems most promising. http://devproconnections.com/entity-framework/working-schema-names-entity-framework-code-first-design

    0 讨论(0)
  • 2020-12-04 18:13

    You could use the ToTable method to specify the schema name. If you do not specify the schema name, EF will by convention use dbo.

    public class MyContext
    {
        private string schemaName = "Foo";
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
             modelBuilder.Entity<MyEntity>().ToTable("MyTable", schemaName);
        } 
    }
    
    0 讨论(0)
  • 2020-12-04 18:15

    For those using Entity Framework 6, just use the HasDefaultSchema method:

    public class Contexto : DbContext
    {
        public DbSet<User> Users { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.HasDefaultSchema("MyDefaultDbSchema");
        }
    }
    
    0 讨论(0)
  • 2020-12-04 18:25

    In EF Code first, by default, everything is set up based on user access with a managerial access "DBO-Schema" in the SQL Server. But if a specific user is defined to work with a database that is common in shared hosting, then there will no longer be Dbo management access. This time the names of our tables are dbo.tableName, for example, someUser.tableName, and inaccuracy of this point makes it impossible to run the program. To modify and explicitly assign a user connected to a database. If you use metadata, the following method should be used:

    [Table("MyTableName", Schema="MySchemaName")]
    public class MyClassName
    {
     //Other Lines...
    }
    

    Or (Whether or not Fluent API is customizable as follows:)

    modelBuilder.Entity<Blog>().ToTable("MyTableName", schemaName:"MySchemaName");
    

    Notice the following:

    a good reference for study: http://www.c-sharpcorner.com/article/fluent-api-in-code-first-approach/

    0 讨论(0)
  • 2020-12-04 18:25

    I would like to add since this is for C#, I have written one below for VB

    Public Class ClientDbContext
    Inherits DbContext
    Public Property Clients As DbSet(Of Client)
    
    Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
        modelBuilder.HasDefaultSchema("dbo")
    End Sub
    End Class
    
    0 讨论(0)
提交回复
热议问题