如何在控制台应用程序中设置默认连接字符串? [英] How do I set a default connection string in a console application?

查看:96
本文介绍了如何在控制台应用程序中设置默认连接字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的具有Web界面的MVC项目中,我习惯于在Web.Config文件中设置连接字符串。但是,现在我正在制作一个沼泽的标准控制台应用程序 - 还有一个数据库挂接,但是如何为应用程序设置全局的连接字符串?



目前,我正在设置

  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屋!

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