Making an Entity Framework Model span multiple databases

后端 未结 3 1644
终归单人心
终归单人心 2020-11-30 04:06

Is it valid to do something such as

CREATE SYNONYM [dbo].[MyTable] FOR [AnotherDatabase].dbo.[MyTable]

and then modify Entity Framework\'s edmx

3条回答
  •  星月不相逢
    2020-11-30 04:48

    I've found that this trick with synonyms works perfectly with the "Code first" approach without any manipulation with edmx files!

    The only thing you have to do, is to "bind" your class to appropriate synonym in the OnModelCreating method of your DataContext.

    For example, if I have a synonym to table Personnel in another DB (and the class name is also Personnel), and synonym's name is "myschema.MySynonym" then the OnModelCreating method should looks like:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.HasDefaultSchema("myschema");
    
            modelBuilder.Entity()
                .ToTable("MySynonym");
    
            Database.SetInitializer(null);
    
            base.OnModelCreating(modelBuilder);
        }
    

提交回复
热议问题