Connection string hell in .NET / LINQ-SQL / ASP.NET

后端 未结 13 1135
渐次进展
渐次进展 2021-01-30 14:29

I have a web application that comprises the following:

  • A web project (with a web.config file containing a connection string - but no data access code in the web pr
13条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-30 14:45

    I had a bit of a struggle with this issue too. I found a solution by using c# partial class definition and extending the datacontext created by dbml designer. This solution quite is similar to tvanfosson's answer. What you have to do is to create partial datacontext class with default constructor getting ConnectionString from settings and in dbml designer DC properties set connection to None. That way connection string will not be the compiled into dll. Datacontext will automatically get connection string from web.config connectionstring settings. I have not tested if this works with app.config also, but I think it should work fine.

    Here is sample of partial DC class:

    namespace MyApplication {
        /// 
        /// Summary description for MyDataContext
        /// 
        /// 
        public partial class MyDataContext
        {
            public MyDataContext() :
                base(global::System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString, mappingSource)
            {
                OnCreated();
            }
        }
    }
    

提交回复
热议问题