如何在控制台应用程序中设置默认连接字符串? [英] How do I set a default connection string in a console application?
问题描述
目前,我正在设置
var dbIndex = new的DbContext();
dbIndex.Database.Connection.ConnectionString =
数据源= USER-PC;初始目录= TextProject.DBContext; +
集成安全= True; MultipleActiveResultSets = True;
但是我必须在所有的函数调用中每次都设置这个connectionstring属性。当我没有web.config时,有没有办法设置全局连接字符串?
所以我想你的说法是实体框架(我认为这是你正在使用)寻找 defaultConnection
连接字符串。
您可以尝试将其放在 app.config
文件按其他人的建议,但我不知道这是否会被EF自动拾取。
如果不行,可以做什么,是创建继承 DbContext
的新类继承
public class MyDbContext :DbContext
{
public MyDbContext():base()
{
var cs = ConfigurationManager.ConnectionStrings [defaultConnection]
.ConnectionString;
this.Database.Connection.ConnectionString = cs;
}
}
In my MVC projects with a web interface, I'm used to setting the Connection String in the Web.Config file.
However, now I'm making a bog standard console application - also with a database hook, but how do I set the connection string globally for the application?
At the moment, I am setting
var dbIndex = new DBContext();
dbIndex.Database.Connection.ConnectionString =
"Data Source=USER-PC;Initial Catalog=TextProject.DBContext;" +
"Integrated Security=True;MultipleActiveResultSets=True";
but I have to set this connectionstring property every time, in all function calls. Is there a way to set a global connection string when I don't have a web.config?
So I think what your saying is that Entity Framework (I assume that is what you are using) looks for defaultConnection
connection string.
You can try putting it in the app.config
file as suggested by others, but I'm not sure if this will be automagically picked up by EF.
What you could do, if it doesn't work, is to create new class which inherits DbContext
-
public class MyDbContext : DbContext
{
public MyDbContext() : base()
{
var cs = ConfigurationManager.ConnectionStrings["defaultConnection"]
.ConnectionString;
this.Database.Connection.ConnectionString = cs;
}
}
这篇关于如何在控制台应用程序中设置默认连接字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!