c# - LINQ 中的连接字符串和数据上下文

标签 c# asp.net linq sql-server-2008

我正在使用 ASP.NET、SQL 2008 和 LINQ 开发一个网站。我想问一下连接字符串。我创建了一个类似的类来获取每个页面中的数据上下文:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public static class DatabaseConnection
{
    static DataClassesDataContext datacontext;    
    public static DataClassesDataContext getConnection()
    {
       datacontext = new DataClassesDataContext(@"Data Source=localhost;Initial Catalog=dbname; Integrated Security=True");
        return datacontext;
    }
}

这是在每个页面中获取连接的正确方法吗?

还有关于“数据源”,当我部署网站时它会是什么?数据源关键字和地址关键字有什么区别?

最佳答案

这是获取数据上下文实例的有效方法,是的。我相信您可以使用数据源服务器

请注意 DataContext 是 IDisposable,因此请确保它在使用后不会闲置,我倾向于这样做:

using (var context = DataHelper.GetContext())
{
   // Stuff.
}

此外,您确实应该将连接字符串放入配置文件中:

<connectionStrings>
   <add name="Live" connectionString="blah;"/>
</connectionStrings>

关于c# - LINQ 中的连接字符串和数据上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6212765/

相关文章:

Java 与 C# : Java and C# subclasses with method overrides output different results in same scenario

c# - 使用 Linq to SQL 进行单元测试实践

c# - onkeydown 类型的事件在服务器端有意义吗?

c# - 使用 ASP.NET 在子域上存储图像

c# - 在哪里可以找到翻译的 Linq to Entity 查询到 Sql

c# - 如何绑定(bind)到父集合 MVVM WPF 中的特定项目

c# - 使用 WCF、Windows Phone 7 和 ASP.Net

c# - 如何配置空 ASP .NET 应用程序以将其发布到 IIS

javascript - 多选下拉菜单在 asp.net 中不起作用

c# - 如何检查数组中的所有值是否相等