实体框架DbContext动态定制与自定义连接字符串 [英] Entity Framework DbContext dynamic instatiation with custom Connection String

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

问题描述

从ObjectContext迁移到DbContext代码生成,我意识到生成的上下文类(从DbContext继承)没有构造函数接收 EntityConnection (如ObjectContext子句)我的应用程序是一个问题,因为我需要使用运行时生成的连接字符串从具体的类型二进制实例化上下文。



任何想法?

解决方案

在继承DbContext的类上,你应该能够指定连接sting的基础构造函数:

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

您将不得不使用SQLConnection构建器:

  SqlConnectionStringBuilder connBuilder = n ew SqlConnectionStringBuilder(dbConnString); 

并在您的构造函数中使用它:

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


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).

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

Any Ideas?

解决方案

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)
    {
    }
}

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天全站免登陆