实体框架:DbContext并设置ProviderName [英] Entity Framework: DbContext and setting the ProviderName

查看:335
本文介绍了实体框架:DbContext并设置ProviderName的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您从DbContext派生并使用无参数的构造函数时,它将从web.config加载连接字符串。您还可以选择使用其他DbContext构造函数之一明确指定connectionString。

When you derive from DbContext and use the parameter-less constructor it will load a connection string from web.config. You also have the option of explicitly specifying the connectionString using one of the other DbContext constructors.

我的特殊情况表明连接字符串不能在web.config中指定,因为在运行时确定服务器/用户名和密码的位置。轻松解决权利?只需使用上述构造函数来指定连接字符串?

My particular situation dictates that the connection string CANNOT be specified in the web.config, as the location of the server/username and password are determined at runtime. Easy fix right? Just use the above mentioned constructor to specify the connection string? Wrong.

问题是当您使用所述构造函数指定连接字符串时,仍会尝试使用默认提供程序,因此,如果您使用一个或多个非标准提供商,像我一样,它不会工作。

The problem is that when you specify the connection string using said constructor, it still attempts to use the default provider, so if you're using one or more non standard providers, as I am, it will not work.

我确定我可以更改web.config中的默认提供程序,但是我想使用多个提供程序所以这不会做。

I'm sure I can change the default provider in the web.config, but I want to use multiple providers so this will not do.

我可以看到的唯一可能的方法是使用ObjectContext而不是DbContext,这似乎允许您指定提供程序数据库连接字符串。

The only possible way around this that I can see is to use ObjectContext instead of DbContext, which seems to allow you to specify the provider along with the database connection string.

还有其他方法吗?我的解决方法是否合理?

Is there any other way to do it? Is my workaround fairly reasonable?

我相信我也可以从ObjectContext实例创建一个DbContext。

I believe I can also create a DbContext from an ObjectContext instance.

推荐答案

手动创建您的 DbConnection ,并将其传递给 DbContext 构造函数,如下所示: / p>

Create your DbConnection manually and pass it to the DbContext constructor as follows:

var conn = DbProviderFactories.GetFactory("MY_CONN_PROVIDER").CreateConnection();
conn.ConnectionString = "MY_CONN_STR";

new DbContext(conn, true);

注意第二个参数 bool contextOwnsConnection code>真。由于您不在其他地方重新使用连接,所以允许上下文管理连接,并在需要时使用 Dispose()

Notice the second parameter bool contextOwnsConnection is true. Since you don't re-use the connection elsewhere, it lets the context manage the connection and Dispose() it when needed.

这篇关于实体框架:DbContext并设置ProviderName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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