[英]Get connection string from web.config to use in EF POCO?
I've noticed that when I create model-first database using EF it is ignoring web.config connection strings and doing it's own thing in the background. 我注意到,当我使用EF创建模型优先的数据库时,它会忽略web.config连接字符串,而在后台执行此操作。 Then I found a way to set my own connection string in constructor like so.
然后,我找到了一种在构造函数中设置自己的连接字符串的方法,如下所示。
public class MainDataContext : DbContext
{
public MainDataContext()
{
this.Database.Connection.ConnectionString = "MY CONNECTION STRING THAT IS ACTUALLY USED";
}
}
Question: How can I force/set it to use connection string from web.config? 问题:如何强制/设置它以使用来自web.config的连接字符串?
I've been told that if you name your connection string just like your data context it will work but it doesen't for me. 有人告诉我,如果您像数据上下文一样命名连接字符串,它将起作用,但不适用于我。 I know for sure that it does not work if I name it
DefaultConnectionString
. 我可以肯定,如果我将其命名为
DefaultConnectionString
,它将无法正常工作。
<add name="MainDataContext" providerName="System.Data.SqlClient"
connectionString="Server=(LocalDB)\\v11.0;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|ProjectDB.mdf;" />
Error occurred when I try to do update-database -v -f
from console. 当我尝试从控制台执行
update-database -v -f
时发生错误。
You can try something like this: 您可以尝试如下操作:
public MainDataContext() :
base(typeof(MainDataContext).Name)
{
}
Are you sure your connection string declaration in the Web.config is correct? 您确定Web.config中的连接字符串声明正确吗? Like this:
像这样:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="MyDatabase" connectionString="server=localhost;User Id=user;password=password;Persist Security Info=True;database=mydatabase" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</configuration>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.