如何在运行时在EF7或EF核心中更改数据库架构 [英] How to change database schema on runtime in EF7 or EF core

查看:94
本文介绍了如何在运行时在EF7或EF核心中更改数据库架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据运行时用户的选择,我的数据库具有不同的架构。

My database have different schema depending on user selections on runtime.

我的代码如下:

public partial class FashionContext : DbContext
{
    private string _schema;

    public FashionContext(string schema) : base()
    {
        _schema = schema;
    }

    public virtual DbSet<Style> Styles { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseSqlServer(@"Server=.\sqlexpress;Database=inforfashionplm;Trusted_Connection=True;");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Style>()
            .ToTable("Style", schema: _schema);
    }
}

经过测试。我使用 schema1创建了一个上下文实例。
到目前为止一切顺利。

Upon testing. I created a context instance with 'schema1'. So far so good.

但是,当我创建另一个具有不同架构 schema2的上下文实例时,所生成的数据仍处于 schema1上。

But when I create another context instance with different schema 'schema2', the resulting data in which the schema is still on 'schema1'.

这里是实现:

using (var db = new FashionContext("schema1"))
        {
            foreach (var style in db.Styles)
            {
                Console.WriteLine(style.Name);
            }
        }

        Console.ReadLine();
        Console.Clear();

        using (var db = new FashionContext("schema2"))
        {
            foreach (var style in db.Styles)
            {
                Console.WriteLine(style.Name);
            }
        }

        Console.ReadLine();

后来我注意到OnModelCreating仅被调用一次,因此在创建时再也不会调用它一个具有相同连接字符串的新上下文实例。

Later I noticed that the OnModelCreating is called only one time, so it is never called again when you create a new context instance of the same connection string.

是否可以在运行时使用动态模式?注意:这在EF6中是可能的

Is it possible to have dynamic schema on runtime? Note: this is possible in EF6

推荐答案

您可以在外部构建模型并将其传递给 DbContext 使用 DbContextOptionsBuilder.UseModel()

You can build the model externally and pass it into the DbContext using DbContextOptionsBuilder.UseModel()

另一种(更高级的)替代方法是 IModelCacheKeyFactory 以将架构考虑在内。

Another (more advanced) alternative is to replace the IModelCacheKeyFactory to take schema into account.

这篇关于如何在运行时在EF7或EF核心中更改数据库架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆