首页 > 代码库 > 动态改变数据库连接 in Entity Framework 5

动态改变数据库连接 in Entity Framework 5

 今天把silverlight 升级到5,ADO.ENT EF也用NUGet升级到5.结果发现5下的EF默认没有4的那种分部方法了。

当然你可以把生成器的属性里面,生成代码的属性替换为default,默认为Note。也可以跟4版本一样有分部方法。

但我发现EF5下面更智能,。更好用。EF的链接字符串有相关的类

EntityConnection

可以操作了。

请参看MSDN:

 http://msdn.microsoft.com/en-us/library/system.data.entityclient.entityconnection.connectionstring.aspx

 

这样动态改变数据库就可以变得更灵活。

只要自定义一个方法,然后返回字符串给EntityConnection链接即可

// Specify the provider name, server and database. string providerName = "System.Data.SqlClient";string serverName = ".";string databaseName = "AdventureWorks";// 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;// 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 = http://www.mamicode.com/@"res://*/AdventureWorksModel.csdl|                            res://*/AdventureWorksModel.ssdl|                            res://*/AdventureWorksModel.msl";Console.WriteLine(entityBuilder.ToString());

动态改变数据库连接 in Entity Framework 5