如何以编程方式设置实体框架代码优先的连接字符串?

How do I programmatically set the connection string for Entity-Framework Code-First?(如何以编程方式设置实体框架代码优先的连接字符串?)

本文介绍了如何以编程方式设置实体框架代码优先的连接字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一些代码,允许我在 SQLCE(在我的开发机器上本地)和完整 SQL(在 AppHarbor 上)之间切换.使用SQL CE,连接字符串都为我处理,但我必须为SQL自己构建它.到目前为止,我的代码如下,但是它给出了这个错误:

I'm trying to write some code that allows me to switch between SQLCE (locally on my dev machine) and full SQL (on AppHarbor). With SQL CE, the connection string is all handled for me, but I have to construct it myself for SQL. My code so far is below, however it gives this error:

不支持关键字:'元数据'

Keyword not supported: 'metadata'

我已经在网上找了几个小时,但所有的解决方案都涉及使用我找不到的ContextBuilder"类(我已经通过 NuGet 包安装了 EF).

I've been looking online for hours, but all the solutions involve using a "ContextBuilder" class which I can't find (I've installed EF via the NuGet package).

这是当前代码(通过 WebActivator 在启动时运行):

Here's the current code (running at startup via WebActivator):

public static void Start()
{
    // Read the details from AppSettings. Locally, these will be empty.
    var databaseHost = ConfigurationManager.AppSettings["DatabaseHost"];
    var databaseName = ConfigurationManager.AppSettings["DatabaseName"];
    var databaseUsername = ConfigurationManager.AppSettings["DatabaseUsername"];
    var databasePassword = ConfigurationManager.AppSettings["DatabasePassword"];

    // Check whether we have actual SQL Server settings.
    if (!string.IsNullOrWhiteSpace(databaseHost) && !string.IsNullOrWhiteSpace(databaseName))
    {
        // Set up connection string for a real live database :-O
        var connectionString = string.Format("metadata=res://*/DB.csdl|res://*/DB.ssdl|res://*/DB.msl;"
            + "provider=System.Data.SqlClient; provider connection string='Data Source={0};"
            + "Initial Catalog={1};User ID={2}; Password={3};MultipleActiveResultSets=True'",
            databaseHost, databaseName, databaseUsername, databasePassword);

        Database.DefaultConnectionFactory = new SqlConnectionFactory(connectionString);
    }
    else
    {
        // Set a custom database initializer for setting up dev database test data.
        Database.SetInitializer<BlogDataContext>(new BlogDataIntializer());

        // Set the connection factory for SQL Compact Edition.
        Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
    }
}

推荐答案

你应该使用 EntityConnectionStringBuilder

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 = @"res://*/AdventureWorksModel.csdl|
                        res://*/AdventureWorksModel.ssdl|
                        res://*/AdventureWorksModel.msl";
Console.WriteLine(entityBuilder.ToString());

using (EntityConnection conn =
new EntityConnection(entityBuilder.ToString()))
{
conn.Open();
Console.WriteLine("Just testing the connection.");
conn.Close();
}

这篇关于如何以编程方式设置实体框架代码优先的连接字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何以编程方式设置实体框架代码优先的连接字符串?

基础教程推荐