Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a default connection string in a console application?

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?

like image 666
RamblerToning Avatar asked Jul 18 '14 15:07

RamblerToning


2 Answers

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;                
    }
}
like image 195
dav_i Avatar answered Nov 15 '22 00:11

dav_i


App.config is the equivalent to a Web.config for console or .exe programs.

  • Add a reference to System.Configuration on any project that you want to use the ConnectionStrings of the app.config
  • Add a AppConfig to your entry point project. This is the project that is executed. (e.g. console .exe)
  • Add the connection string in the <connectionStrings></connectionStrings> section of the app.config

Now place the connection string in your app.config

string connStr =ConfigurationManager.ConnectionStrings["ConnName"]
  .ConnectionString;

App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="ConnName" connectionString="Data Source=USER-PC;Initial Catalog=TextProject.DBContext;Integrated Security=True;MultipleActiveResultSets=True" />
 </connectionStrings>
</configuration> 
like image 30
T McKeown Avatar answered Nov 14 '22 22:11

T McKeown