我有一个连接到sqlexpress的c#.net 4.0应用程序。我想进行更改,以便连接到localDB。我将重用相同的mdf。
目前,配置文件包含以下条目
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=.\EMSERVER; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
还在代码中
string providerName =&#34; System.Data.SqlClient&#34 ;;
// Initialize the connection string builder for the
// underlying provider.
SqlConnectionStringBuilder sqlBuilder =
new SqlConnectionStringBuilder();
// Set the properties for the data source.
sqlBuilder.DataSource = serverName;
sqlBuilder.InitialCatalog = databaseName;
sqlBuilder.IntegratedSecurity = true;
sqlBuilder.Enlist = true;
sqlBuilder.MultipleActiveResultSets = true;
// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();
// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder =
new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = providerName;
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;
// Set the Metadata location.
entityBuilder.Metadata = @"res://*/TrendDataModel.csdl|
res://*/TrendDataModel.ssdl|
res://*/TrendDataModel.msl";
return entityBuilder.ToString();
我们应该同时拥有代码和app.config吗?如何更改它以连接到c:\ temp中的test.mdf文件。或者我是否足以直接在代码中更改连接字符串?
答案 0 :(得分:0)
EF提供了两种类型的DbContext / ObjectContext构造函数方法。
其中一个采用连接字符串的名称(来自配置文件),另一个采用EntityConnection实例,它是ConnectionString的包装器。这样你就可以使用其中一种。