none
Provide connection string to DbContext at runtime or registry RRS feed

  • Question

  • Hi there,

    Is there a way to provide the connection string to my DbContext at runtime? Ideally, I would read it from Registry.

    I've tried the following code:

    public class MyContext : DbContext
    {
       public MyContext()
       {
             this.Database.Connection.ConnectionString = @"data source=.\SQLEXPRESS;initial catalog=YYYYYYY;Integrated Security=True;multipleactiveresultsets=True;App=EntityFramework";
        }
    }

    However, if the DB doesn't exist, I get an exception:

         The underlying provider failed on Open. Cannot open database \"YYYYYYY\" requested ...

    Normally, with the connection string in app.config, the database would get created by the framework, so that's what I'm expecting.

    Is there a way?

    Thanks.

    -D

    Tuesday, May 22, 2012 8:04 PM

Answers

  • Hi DashNYC,

    Welcome to MSDN Forum.

    Please refer to the code below.

    class Program
        {        
                static void Main(string[] args)
                {
                    string str = Console.ReadLine();
                    TestContext context = new TestContext(str);
                    context.Database.CreateIfNotExists();
                }               
        }
    
        class Test
            {
                public int ID { get; set; }
                public string Name { get; set; }
            }
    
        class TestContext : DbContext
        {
            public TestContext(string str):base(str)
            {
                this.Database.Connection.ConnectionString = str;
            }
            public DbSet<Test> testSet { get; set; }
        }

    Best Regards

    Allen Li [MSFT]
    MSDN Community Support | Feedback to us

    • Marked as answer by DashNYC Wednesday, May 23, 2012 2:57 PM
    Wednesday, May 23, 2012 7:29 AM
    Moderator