1

I have a c# console app that uses entity framework. In the app config file I define the connection string

<connectionStrings>
<add name="DefaultConnection" connectionString="Provider=Microsoft.ACE.OleDb.12.0;Data source={argument from Main function}" providerName="JetEntityFrameworkProvider" />
</connectionStrings>

My context.cs

public class SinergyContext : DbContext
{
    public SinergyContext() : base("name=DefaultConnection") { }

    public DbSet<RejectedData> RejectedErrors { get; set; }
}

My Program.cs

static void Main(string[] args)
    {
        // arg[0] contains the connection string data source

Is it possible to set the connection string in Program.cs file ?

raihane
  • 39
  • 9
  • You can follow this other SO example: https://stackoverflow.com/q/15631602/1188197. Read in your connection string and create the db connection from the string. – EspressoBeans May 25 '21 at 16:56

3 Answers3

2

Change your DBContext to accept a custom connection string:

public class SinergyContext : DbContext
{
    public SinergyContext(string cs) : base(cs) { }

    public DbSet<RejectedData> RejectedErrors { get; set; }
}

Then instantiate it via:

var db = new SinergyContext("my connection string");

If you have to use a provider, you can use a EntityConnectionStringBuilder:

var builder = new EntityConnectionStringBuilder
{
    Provider = "JetEntityFrameworkProvider",
    ProviderConnectionString = $"Provider=Microsoft.ACE.OleDb.12.0;Data source={args[0]}"
};
var db = new SinergyContext(builder.ToString());
mxmissile
  • 11,464
  • 3
  • 53
  • 79
  • Is it possible to add a provider (eg. JetEntityFrameworkProvider) in the instantiation of SinergyContext ? Because without this provider the connection to Access database doesn't work. That is why the app.config was useful because it contains the provider – raihane May 27 '21 at 13:23
  • Is this EF Core? Or EF 6? – mxmissile May 27 '21 at 13:50
  • Thank you @mxmissile for your help. I did find a way to solve my problem. I published the answer. – raihane May 27 '21 at 15:18
1

you can used ConfigurationManager.ConnectionStrings to get ConnectionString of app config

Example:

system.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

or create the context and get its properties

context = new SinergyContext();
jcHernande2
  • 301
  • 2
  • 6
0

Finally I found a way to pass values to app.config using c# (in main.cs file). Here is how :

static void Main(string[] args)
{
  Configuration config = ConfigurationManager
    .OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location);

  ConnectionStringsSection section = 
    (ConnectionStringsSection)config.GetSection("connectionStrings");

  section.ConnectionStrings["DefaultConnection"].ConnectionString += args[0];

  config.Save();
}
raihane
  • 39
  • 9