如何以编程方式为Entity-Framework Code-First设置连接字符串?

时间:2011-05-14 16:15:12

标签: sql-server asp.net-mvc entity-framework ef-code-first

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

  

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

我一直在网上看了好几个小时,但是所有解决方案都涉及使用我找不到的“ContextBuilder”类(我已经通过NuGet包安装了EF)。

这是当前代码(通过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");
    }
}

4 个答案:

答案 0 :(得分:43)

您应该使用 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();
}

答案 1 :(得分:12)

在Entity-Framework Code-First中首先使用SqlConnection。您不能使用EntityConnectionStringBuilder,因为在代码优先时没有元数据文件。

答案 2 :(得分:8)

您也可以直接在上下文中进行设置。您必须将mdf附加到要首先使用的SqlServer实例。不完全优雅,但它对我有用

public void DoImportWork()
{
   var ctx = new StatisticsContext(); << your DbContext 

   ctx.Database.Connection.ConnectionString = @"Data Source=localhost\SQLEXP;AttachDbFilename=""C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXP\MSSQL\DATA\StatisticsData.mdf"";Integrated Security=True";

   ctx.Database.Connection.Open();
}
像往常一样,EF会在您将第一行添加到上下文时自动生成所有内容。

答案 3 :(得分:0)

使用connection string创建Entity Framework时,此代码会很方便

public string GenerateEFConnectionString(string serverName, string dbName,string ModelName,string userName,string password)
{   
    // Initialize the connection string builder for the underlying provider.
    SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
    sqlBuilder.DataSource = serverName;
    sqlBuilder.InitialCatalog = dbName;
    //sqlBuilder.IntegratedSecurity = false;
    sqlBuilder.UserID = userName;
    sqlBuilder.Password = password;
    sqlBuilder.MultipleActiveResultSets = true;

    // Initialize the EntityConnectionStringBuilder.
    EntityConnectionStringBuilder entityBuilder =
        new EntityConnectionStringBuilder();

    entityBuilder.Provider = "System.Data.SqlClient";
    entityBuilder.ProviderConnectionString = sqlBuilder.ToString();

    // Set the Metadata location.
    entityBuilder.Metadata = string.Format("res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl",ModelName); 
    return (entityBuilder.ToString().Replace("\"","&quot;"));
}

可以从一组参数中调用

GenerateEFConnectionString("srv","db","mod","vinodsrivastav","nopassword");

生成这样的connection string

metadata=res://*/mod.csdl|res://*/mod.ssdl|res://*/mod.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=srv;Initial Catalog=db;User ID=vinodsrivastav;Password=nopassword;MultipleActiveResultSets=True&quot;