EntityFramework 6基于代码的数据库优先连接字符串配置

时间:2016-07-28 12:33:40

标签: c# .net entity-framework entity-framework-6

我正在尝试在没有app.config的情况下使现有应用程序工作(由于非常特定的环境,它是必需的)。问题是它严重依赖EntityFramework 6来处理SQL-Server。

我正在尝试使用code-based configuration,但我无法弄清楚如何通过我的配置类提供正确的连接字符串。

我做了一个配置类:

public class MyConfiguration : DbConfiguration
{
    public MyConfiguration()
    {
        SetDefaultConnectionFactory(new MyConnectionFactory());
        SetProviderServices("System.Data.SqlClient", System.Data.Entity.SqlServer.SqlProviderServices.Instance);
    }
}

然后将它提供给我的DbContext(由EF自动从bd生成):

[DbConfigurationType(typeof(MyConfiguration))]
public partial class TestModelEntities
{           
}

使用自定义连接工厂:

public class MyConnectionFactory : IDbConnectionFactory
{
    public DbConnection CreateConnection(string nameOrConnectionString)
    {
        var newConnStringBuilder = new SqlConnectionStringBuilder
        {
            UserID = "user",
            Password = "pass",
            InitialCatalog = "databaseName",
            DataSource = "serverName"
        };

        var entityConnectionBuilder = new EntityConnectionStringBuilder
        {
            Provider = "System.Data.SqlClient",
            ProviderConnectionString = newConnStringBuilder.ToString(),
            Metadata = @"res://*/TestModel.csdl|
                            res://*/TestModel.ssdl|
                            res://*/TestModel.msl"
        };

        var newDbConnect = new EntityConnection(entityConnectionBuilder.ToString());
        return newDbConnect;
    }
}

然而。当我测试它时,我得到一个UnintentionalCodeFirstException。为什么?我错过了什么?

2 个答案:

答案 0 :(得分:4)

您应该通过:base(connectionString)为您的上下文提供连接字符串。创建一个类如下:

public class ConnectionStringBuilder
{
    public static string Construct()
    {
        var newConnStringBuilder = new SqlConnectionStringBuilder
        {
            UserID = "user",
            Password = "pass",
            InitialCatalog = "databaseName",
            DataSource = "serverName"
        };

        var entityConnectionBuilder = new EntityConnectionStringBuilder
        {
            Provider = "System.Data.SqlClient",
            ProviderConnectionString = newConnStringBuilder.ToString(),
            Metadata = @"res://*/TestModel.csdl|
                            res://*/TestModel.ssdl|
                            res://*/TestModel.msl"
        };

        return entityConnectionBuilder.ToString();
    }
}

然后将Context构造函数修改为如下所示:

public DbContext()
    : base(ConnectionStringBuilder.Construct())
{
}

现在应该可以正常工作了。 (source

答案 1 :(得分:0)

公开静态方法可能会在并发用户场景中构成危险。尝试使用单例模式创建数据库连接字符串。