问题描述
我正在尝试使现有应用程序在没有 app.config 的情况下工作(由于非常特定的环境而需要它).问题是它严重依赖 EntityFramework 6 来处理 SQL-Server.
I'm attempting to make an existing application work without an app.config (it is required due to a very specific environment). Problem is that it's heavily relying on EntityFramework 6 to work with an SQL-Server.
我正在尝试使用 基于代码的配置,但我不知道如何通过我的配置类提供正确的连接字符串.
I'm trying to use a code-based configuration, but I can't figure out how to provide a correct connection string through my configuration class.
我做了一个配置类:
public class MyConfiguration : DbConfiguration
{
public MyConfiguration()
{
SetDefaultConnectionFactory(new MyConnectionFactory());
SetProviderServices("System.Data.SqlClient", System.Data.Entity.SqlServer.SqlProviderServices.Instance);
}
}
然后将其提供给我的 DbContext(由 EF 自动从 bd 生成):
Then provided it to my DbContext (Generated by EF automatically from 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
.为什么?我错过了什么?
However. When I test it, I get an UnintentionalCodeFirstException
. Why? What am I missing?
推荐答案
你应该通过 :base(connectionString) 为你的上下文提供连接字符串.如下创建一个类:
You should provide connection string to your context via :base(connectionString). Create a class as below:
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 构造函数,如下所示:
Then modify your Context constructor to look like this:
public DbContext()
: base(ConnectionStringBuilder.Construct())
{
}
现在应该可以正常工作了.(来源)
It should work fine now. (source)
这篇关于EntityFramework 6 基于代码的数据库优先连接字符串配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!