rlcrews
rlcrews

Reputation: 3562

How to set a EF code first connection string at runtime

I'm missing something. I have a small project where I am trying to insert some data into a database. When I created the model I used Code First against an existing database. I wanted to make the app capable of point to any server at runtime. This is a down and dirty utility app an and running internally but I need some flexibility when running it. From reading some msdn articles I saw where I could extend the DBContext on initialization so I did the following:

added a parameter to the initialization:

 public OtherEventModel(string ConnectionString)
            : base("name=OtherEventModel")
        {...

Then within my code I built the connection string based upon the properties passed in from the UI:

private OtherEventModel ConnectToServer(string server, string username, string password)
        {
            try
            {

                SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder
                {
                    DataSource =  server,
                    UserID = username,
                    Password = password,
                    InitialCatalog = "My_Database",
                    IntegratedSecurity = true
                };

                var connection = sqlBuilder.ToString();
                ModelContext = new OtherEventModel(connection);

                return ModelContext;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Error connecting to server {0}", ex.Message));
            }

I can see the connection string created however when I run the code I receive an exception that the connection string (what should be in app.config could not be found). Which I do not have a connection string or key within app config since I was trying to inject the connection string in at runtime.

Error:

Error inserting data No connection string named 'OtherEventModel' could be found in the application config file

I was under the impression from what I have read that Code first uses a standard SQL connection string and does not require the EntityConnectionStringBuild (used for object first dev)

Can someone point me in the right direction as to what I have missed or what I am doing wrong.

Thanks in advance

Upvotes: 0

Views: 760

Answers (1)

Mr. B
Mr. B

Reputation: 2975

You're almost there, just pass the connection string to the base:

public OtherEventModel(string ConnectionString)
       : base(ConnectionString)

Make sure you comment the throw line in the method below. Unfortunately you have to do this again every time you update the model.

Upvotes: 1

Related Questions