在.NET / LINQ-SQL / ASP.NET连接字符串地狱 [英] Connection string hell in .NET / LINQ-SQL / ASP.NET

查看:141
本文介绍了在.NET / LINQ-SQL / ASP.NET连接字符串地狱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web应用程序,包括以下内容:

I have a web application that comprises the following:

  • 在Web项目(包含连接字符串web.config文件 - 但没有数据访问code。在Web项目)
  • 在使用LINQ-SQL类提供实体的web项目的用户界面的数据访问项目(这个项目有一个设置文件和一个app.config - 这两者都连接字符串)

当我创建和部署,有在Bin目录中的数据访问的.dll没有设置文件或app.config中,但将web.config文件中的连接字符串不相应地更改数据库 - 所以连接字符串必须被编译成数据访问DLL。

When I build and deploy, there is no settings file or app.config in the Bin directory with the data access .dll, but changing the connection string in the web.config file doesn't change the database accordingly - so the connection string must be compiled into the data access dll.

我需要一个配置文件为我的整个部署 - 网站,数据访问的dll,一切 - 有哪个被使用一个连接字符串。目前似乎有习惯或硬codeD所有的地方多个连接字符串。

What I need is one config file for my entire deployment - website, data access dlls, everything - that has one connection string which gets used. At the moment there appear to be multiple connection strings getting used or hardcoded all over the place.

我最好如何解决这个烂摊子?

How do I best resolve this mess?

感谢您的帮助。

推荐答案

我从来没有用的数据访问层问题的(DAL)能够使用连接字符串从我的的web.config 文件。通常我刚刚从DAL复制连接字符串部分,并将其粘贴到的web.config 。我使用的是DBML设计器来创建数据上下文。

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.

如果这不会为你工作,你可以指定数据上下文构造连接字符串。在您的Web项目必须加载你的设置,包括您的连接字符串静态类,当你创建你的DAL对象(或数据的情况下,如果直接创建它)只是把它传递到构造函数。

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))
{
   ...
}

这篇关于在.NET / LINQ-SQL / ASP.NET连接字符串地狱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆