当我尝试使用取ConStr参数的构造函数进行连接时,应用程序会抛出以下异常。但如果我使用第一个不取ConStr参数的构造函数,则连接成功。
抛出的异常信息:Failed to set Database.DefaultConnection:
Failed to set Database.DefaultConnectionFactory to an instance of the 'Npgsql.NpgsqlFactory, Npgsql' type as specified in the application configuration. 详见内部异常。
内部异常信息
在类型'Npgsql.NpgsqlFactory'上找不到构造函数。
Entity Framework - Version 6.1.3,
EntityFramework6.Npgsql - Version 3.1.1,
Npgsql - Version 3.1.7
在你的DbContext实现命名空间中包含以下内容。
using Npgsql;
using System.Data.Entity;
class NpgSqlConfiguration : DbConfiguration
{
public NpgSqlConfiguration()
{
var name = "Npgsql";
SetProviderFactory(providerInvariantName: name,
providerFactory: NpgsqlFactory.Instance);
SetProviderServices(providerInvariantName: name,
provider: NpgsqlServices.Instance);
SetDefaultConnectionFactory(connectionFactory: new NpgsqlConnectionFactory());
}
}
在你的依赖注入中这样实例化你的上下文 或者你决定创建上下文的任何地方。
MyDbContext _dbContext;
var connectionString = Config.GetConnectionString("MyConnectionStringName");
NpgsqlConnection connection = new Npgsql.NpgsqlConnection(connectionString);
_dbContext = new MyDbContext(connection);