在Visual Studio 2008中使用Linq to SQL在dbml文件中设置连接字符串 [英] Setting Connection string in dbml files using Linq to SQL in Visual Studio 2008

查看:92
本文介绍了在Visual Studio 2008中使用Linq to SQL在dbml文件中设置连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与数据库"TestDB"一起使用的应用程序.在开发应用程序时,我使用的是linq到sql,并通过拖放到TestDB.dbml文件来添加数据表,并且.net可能会自动将连接字符串设置为计算机上的本地sql服务器.该应用程序应该在某些基于Windows的仪器上启动.并且数据库将在这些工具中处于本地状态.

I have an application that works with a database "TestDB". At the time I was developing the application I was using linq to sql and adding my data tables by dragging and dropping to the TestDB.dbml file and probably .net automatically sets the connection string to the local sql server on my machine. The application is supposed to launch on some windows based instruments. and the database will be local in those instruments.

现在,如何更改连接字符串以确保仪器内部的本地数据库适合我的应用程序?

Now, how can I change the connection string to make sure that the local database inside the instrument will be targeted for my application?

我还向数据库中添加了用户名和密码,因此不会是Windows身份验证连接,我的猜测是用户名和密码应该是连接字符串的一部分.

Also, I added username and password to my database so it will not be windows Authentication connection and my guess is that username and password should be part of the connection string.

推荐答案

在代码中创建DataContext时,将传入ConnectionString.因此,您可以将其存储在配置文件中,然后使用ConfigurationManager抓取ConnectionString并使用它来创建DataContext,如下所示:

When you create your DataContext in your code you will pass in the ConnectionString. So you can store that in a config file and then using ConfigurationManager grab the ConnectionString and use it to create your DataContext like so:

public class SomeService
    {
        private SomeDataContext _db = null;

        public SomeService() 
        {
            _db = new SomeDataContext(ConfigurationManager.ConnectionStrings["SomeSqlServer"].ConnectionString);
        }

        public SomeService(string connectionString)
        {
            _db = new SomeDataContext(connectionString);
        }

        public SomeDataContext DB
        {
            get
            {
                return _db;
            }
        }

        // whatever methods you want to use that access this DataContext
}

这篇关于在Visual Studio 2008中使用Linq to SQL在dbml文件中设置连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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