在EF 7中配置多个dbcontext [英] Configure more than one dbcontext in EF 7

查看:390
本文介绍了在EF 7中配置多个dbcontext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用VS 2015 ctp创建了一个Web入门应用程序,我想添加一个内存中的存储来做一些测试,但是当我尝试读取数据时,会收到此消息

I created a web starter application with VS 2015 ctp, and I would like to add an in-memory store to do some test, but when I try to read the data, I get this message


数据存储区'SqlServerDataStore''InMemoryDataStore'可用
。上下文只能配置为使用单个数据
存储。设置
服务时,通过覆盖
DbContext类或AddDbContext方法中的OnConfiguring来配置数据存储。

The data stores 'SqlServerDataStore' 'InMemoryDataStore' are available. A context can only be configured to use a single data store. Configure a data store by overriding OnConfiguring in your DbContext class or in the AddDbContext method when setting up services.

如何创建第二个数据存储区?现在,在 ConfigureService 方法

How can I do to create a second datastore? Now I have this row in the ConfigureService method

AddEntityFramework(Configuration)
  .AddSqlServer()
  .AddDbContext<ApplicationDbContext>()
  .AddInMemoryStore()
  .AddDbContext<WorkModel>( options => { options.UseInMemoryStore(persist: true); });

编辑
情况似乎不清楚。
我有相同的sql服务器dbcontext,并且我想添加另一个dbcontext,该文件完全分开,我想在内存中运行。我正在研究如何配置两个不同的dbcontext,在这种情况下使用两个不同的数据存储。

Edit: Looks like the scenario is not clear. I have the identy sql server dbcontext, and I want to add a second dbcontext, totally separated, that I want to run in memory. I'm looking how configure two different dbcontext, in this case using two different datastores.

第一个是Identity ApplicationDbContext,另一个是这样的:

The first one is the Identity ApplicationDbContext, and another is something like this:

public class WorkModel : DbContext
{

    public DbSet<Cliente> Clienti { get; set; }
    public DbSet<Commessa> Commesse { get; set; }

    protected override void OnModelCreating(ModelBuilder builder) {
        builder.Entity<Cliente>().Key(cli => cli.ClienteId);
        builder.Entity<Commessa>().Key(cli => cli.CommessaId);
    }
}

或者您喜欢任何自定义dbcontext

Or whatever custom dbcontext do you like

推荐答案

可能将一种 DbContext 类型与多个数据存储区一起使用。但是,它在您调用 .AddDbContext()时效果不佳。这是一个将 .ConfigureServices()完全排除在外的示例。

It's possible use one DbContext type with multiple data stores. It won't however play well with your calls to .AddDbContext(). Here is an example of how to do it taking .ConfigureServices() entirely out of the picture.

class MyContext : DbContext
{
    bool _useInMemory;

    public MyContext(bool useInMemory)
    {
        _useInMemory = useInMemory;
    }

    protected override void OnConfiguring(DbContextOptions options)
    {
        if (_useInMemory)
        {
            options.UseInMemoryStore(persist: true);
        }
        else
        {
            options.UseSqlServer();
        }
    }
}

然后可以实例化上下文

var inMemoryContext = new MyContext(useInMemory: true);
var sqlServerContext = new MyContext(useInMemory: false);

这篇关于在EF 7中配置多个dbcontext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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