JoeS
JoeS

Reputation: 1425

Make .dbml file in a class library use connectionstring from config file without subclassing it

I have a class library that is referenced from a web application. The class library defaults to using TestProject.Properties.Settings.Default.NFU_Custom_Website_DataConnectionString1. I would like it to get the connectionstring from ConfigurationManager.ConnectionStrings.

I can't change the .designer.cs file because it will get overwritten. If possible I would like to avoid creating a class which inherits from the .dbml file and setting the connection string in there. My boss recommends creating a web application project and deleting all of the default.aspx etc files from it and using that instead of a class library, is this a viable solution?

Thanks

Joe

Upvotes: 1

Views: 2351

Answers (1)

Andrew McLachlan
Andrew McLachlan

Reputation: 349

You can do that. We had done that inadvertently and I got this problem when I switched to a class library. Rather than switch back I found the answer here: Point connectionstring in dbml to app.config

In summary:

  1. Set the connection property of the DBML to (none) in the designer. This will remove the default constructor from the DB Context class.
  2. Create a partial class for your DB Context with a default constructor:

    using System.Configuration;

    namespace TestProject
    {
        public partial class MyDBContext
        {
            public MyDBContext() : base(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString)
            {
                OnCreated();
            }
        }
    }

Upvotes: 3

Related Questions