在代码中指定Asp.net LocalSqlServer连接字符串

时间:2014-08-18 15:23:26

标签: asp.net

通常,我们在web.config中定义连接字符串

有没有办法可以在代码中指定连接字符串,比如Application_Start?

通常用于连接aspnetdb的连接字符串 例如:

    

2 个答案:

答案 0 :(得分:1)

如果你使用实体框架,你可以使用SqlConnectionStringBuilder类。

来自MSDN的示例:

Sub Main()
' Create a new DbConnctionStringBuilder, and add items 
' to the internal collection of key/value pairs. 
Dim builder As New DbConnectionStringBuilder()
builder.Add("Data Source", "c:\MyData\MyDb.mdb")
builder.Add("Provider", "Microsoft.Jet.Oledb.4.0")
builder.Add("Jet OLEDB:Database Password", "*******")
builder.Add("Jet OLEDB:System Database", _
    "c:\MyData\Workgroup.mdb")
' Set up row-level locking.
builder.Add("Jet OLEDB:Database Locking Mode", 1)

' Display the contents of the connection string, which 
' will now contain all the key/value pairs delimited with 
' semicolons.
Console.WriteLine(builder.ConnectionString)
Console.WriteLine()

' Clear the DbConnectionStringBuilder, and assign a complete 
' connection string to it, to demonstrate how 
' the class parses connection strings.
builder.Clear()
builder.ConnectionString = _
    "Data Source=(local);Initial Catalog=AdventureWorks;" & _
    "Integrated Security=SSPI" 

' The DbConnectionStringBuilder class has parsed the contents,  
' so you can work with any individual key/value pair.
builder("Data Source") = "."
Console.WriteLine(builder.ConnectionString)
Console.WriteLine()

' Because the DbConnectionStringBuilder class doesn't  
' validate its key/value pairs, you can use this class 
' to store any semicolon-delimited list. The following 
' snippet places an arbitrary string into the ConnectionString 
' property, changes one of the values, and then displays the 
' resulting string.
builder.Clear()
builder.ConnectionString = _
    "Value1=10;Value2=20;Value3=30;Value4=40"
builder("Value2") = 25
Console.WriteLine(builder.ConnectionString)
Console.WriteLine()

builder.Clear()
Try 
    ' Assigning an invalid connection string 
    ' throws an ArgumentException.
    builder.ConnectionString = "xxx" 

Catch ex As ArgumentException
    Console.WriteLine("Invalid connection string.")
End Try

Console.WriteLine()
Console.WriteLine("Press Enter to finish.")
Console.ReadLine()
End Sub

答案 1 :(得分:0)

如果您正在使用Entity Framework,则可以使用Entity ConnectionString构建器

            internal static EntityConnectionStringBuilder GetConnectionString()
            {
                // Specify the provider name, server and database. 
                string providerName = "System.Data.SqlClient";
                string serverName;
                string databaseName;

                databaseName = "MyDatabase";
                serverName = "localhost";


                // Initialize the connection string builder for the underlying provider.
                SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder()
                {
                    // Set the properties for the data source.
                    DataSource = serverName,
                    InitialCatalog = databaseName,
                    IntegratedSecurity = false,

                    UserID = "sqluser",
                    Password = "password",
                };

                // Build the SqlConnection connection string. 
                string providerString = sqlBuilder.ToString();

                // Initialize the EntityConnectionStringBuilder.
                EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder()
                {
                    //Set the provider name.
                    Provider = providerName,

                    // Set the provider-specific connection string.
                    ProviderConnectionString = providerString,

                    // Set the Metadata location.
                    Metadata = "@ENTER META DATA HERE"
                };

                return entityBuilder;
            }
        }

然后,您可以向实体添加构造函数以接受连接字符串(从Here借来)

public partial class MyEFEntities
{
    public MyEFEntities(string connectionstring)
        : base(connectionstring)
    {
    }
}

最后,您可以这样称呼它:

using (var connection = DAL.MyEFEntities(GetConnectionString().ToString()))
{
   // Do work here
}