Using Entity Framework 6 with Multiple DB Schemas but using One DBContext

后端 未结 5 1819
甜味超标
甜味超标 2020-12-13 17:43

I have an application using EF as ORM. The database used to have one schema, dbo and everything was working fine. I recently organized my tables into 4 different schemas. So

相关标签:
5条回答
  • 2020-12-13 18:11

    In addition to the responce of Gert Arnold, you can also use Table attribute in your entity:

    using System.ComponentModel.DataAnnotations.Schema;
    
    [Table("t_Department", Schema = "school")]
    public class Department
    {
        public int Id { get; set; }
    
        public string Name { get; set; }
    }
    
    0 讨论(0)
  • 2020-12-13 18:20

    @GertArnold is spot on with his answer. However for pure syntactic candy you can also do this via a convention to pull the schema from the namespace of your models. We found this useful dealing with multiple schemas

    modelBuilder.Types().Configure(e => {
            var schema = e.ClrType.Namespace.Split('.').Last().ToLower();
            var name = entity.ClrType.Name;
            return entity.ToTable(name, schema);
    });
    

    the above will take the final component of the namespace and use it as the schema name. This avoids the need for customising the table binding for every entity.

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

    In my case, it's possibly that I use DB First to generate my EDMX file, so it doesn't invoke OnModelCreating method.

    I finally remove all store:Schema="YourSchema" and Schema="YourSchema" in EDMX file, and I do it by write a bat file with powershell command as below, and execute the bat in the Projec Pre-Build Event:

    powershell -Command "$varStr='store:Schema=""abcd""""'; $filePath='%~dp0SomeFolder\SomeFile.edmx'; (gc $filePath) -replace $varStr, '' | Out-File $filePath"
    
    0 讨论(0)
  • 2020-12-13 18:23

    ok, you put schema o class header etc but where you define that schema? for example:

    [Table("Test", Schema = "test1")]
    public class Test
    {
        public int Id { get; set; }
    }
    
    [Table("Test2", Schema = "test2")]
    public class Test2
    {
        public int Id { get; set; }
    }
    

    but where to put test1 and test2? different DbContexts or where?

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

    You can map each table to its own schema by fluent mapping only. In your DbContext subtype you should override OnModelCreating (if you haven't done so already) and add statements like this:

    modelBuilder.Entity<Department>()  
        .ToTable("t_Department", "school");
    

    Entities that you don't map like this explicitly will be placed in the default dbo schema, or you can provide your own default by

    modelBuilder.HasDefaultSchema("sales");
    

    (summarized from here)

    0 讨论(0)
提交回复
热议问题