具有自定义连接字符串的实体框架DbContext动态实例化 [英] Entity Framework DbContext dynamic instantiation with custom Connection String

查看:91
本文介绍了具有自定义连接字符串的实体框架DbContext动态实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从ObjectContext迁移到DbContext代码生成后,我意识到生成的上下文类(继承自DbContext)没有构造函数,该构造函数既不接收 connectionString ,也不接收 EntityConnection (如ObjectContext子级

Migrating from ObjectContext to DbContext code-generation, I realized that context class generated (which inherits from DbContext) has no constructor that receives connectionString neither EntityConnection (like ObjectContext child class had).

这是我的应用程序中的一个问题,因为我需要使用运行时生成的连接字符串从具体Type动态实例化上下文。

This is a problem in my application since I need to instantiate my context dynamically from the concrete Type, using a runtime generated connection string.

推荐答案

在继承DbContext的类上,您应该能够指定采用连接字符串的基本构造函数:

On your class that inherits the DbContext, you should be able to specify the base constructor that takes the connection sting:

public class MyDbContext : DbContext
{
    public MyDbContext(string connString)
        : base(connString)
    {
    }
}

不过,您将必须使用SQLConnection构建器:

You will have to use the SQLConnection builder though:

SqlConnectionStringBuilder connBuilder= new SqlConnectionStringBuilder(dbConnString);

并在构造函数中使用它:

And use it in your constructor:

MyDbContext dbContext = new MyDbContext(connBuilder.ToString());

这篇关于具有自定义连接字符串的实体框架DbContext动态实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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