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

后端 未结 13 1132
渐次进展
渐次进展 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:54

    I've never had a problem with the Data Access Layer (DAL) being able to use the connection strings from my web.config file. Usually I just copy the connection strings section from the DAL and paste it into the web.config. I'm using the DBML designer to create the data context.

    If this won't work for you, you can specify the connection string in the data context constructor. In your web project have a static class that loads your settings, including your connection strings, and when you create your DAL object (or data context, if creating it directly) just pass it in to the constructor.

    public static class GlobalSettings
    {
        private static string dalConnectionString;
        public static string DALConnectionString
        {
           get
           {
               if (dalConnectionString == null)
               {
                  dalConnectionString = WebConfigurationManager
                                          .ConnectionStrings["DALConnectionString"]
                                            .ConnectionString;
               }
               return dalConnectionString;
           }
        }
    }
    ...
    
    using (var context = new DALDataContext(GlobalSettings.DALConnectionString))
    {
       ...
    }
    

提交回复
热议问题