You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在运行时为Entity Framework 6注册SQL提供程序并解决连接问题?

EF6合并DLL部署到BPM工具后出现SQL连接超时错误

我正在开发一款基于.NET Framework 4.8、使用Entity Framework 6的DLL,要求在运行时设置SQL提供程序,让DLL无需配置文件就能独立运行——因为它会被上传到BPM工具按需部署,要避免修改多份配置文件。

为了兼容Entity Framework,我用ILMerge把我的DLL、EntityFramework.dll和EntityFramework.SqlServer.dll合并成了单个DLL。

之前我通过给DbContext添加接收连接字符串的构造函数,实现了运行时指定连接字符串,在Visual Studio中测试本地数据库完全没问题。

但把DLL上传到BPM工具并调用测试方法后,出现了以下错误:

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'. Make sure the provider is registered in the 'entityFramework' section of the application config file

我尝试了多种解决方案,最新的方案是修改DbConfiguration,解决了提供程序的问题,但又出现了新错误:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

这个错误会在启动60秒后出现,符合连接默认超时的特征。

DbContext和DbConfiguration代码

public class SqlProviderDbConfiguration : DbConfiguration
{
    public SqlProviderDbConfiguration()
    {
        // 以编程方式注册提供程序
        SetDefaultConnectionFactory(new SqlConnectionFactory());
        SetProviderServices("System.Data.SqlClient", SqlProviderServices.Instance);
    }
}

[DbConfigurationType(typeof(SqlProviderDbConfiguration))]
public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    static BloggingContext()
    {
        // 设置配置
        DbConfiguration.SetConfiguration(new SqlProviderDbConfiguration());
    }

    // 通过调用接收连接字符串的DbContext构造函数指定连接字符串
    public BloggingContext(string connectionString) : base(connectionString)
    {
    }

    // 默认构造函数,没有它无法编译,我的代码里不会用到,但EF正常工作时仍会运行
    public BloggingContext()
    {
    }
}

被调用的测试方法代码

public int TestConnection(string blogName, string connectionString)
{
    // 若数据库架构不是最新版本则更新
    Database.SetInitializer(new MigrateDatabaseToLatestVersion<BloggingContext, Configuration>());

    int blogId = -1;
    using (var db = new BloggingContext(connectionString))
    {
    
        var blog = new Blog { Name = blogName };
        db.Blogs.Add(blog);
        db.SaveChanges();

错误出现在db.Blogs.Add(blog);这一行。

我在Visual Studio中使用的连接字符串是Data Source=(localdb)\mssqllocaldb;Initial Catalog=EmbeddedEntityFrameworkTest.BloggingContext;Integrated Security=True;MultipleActiveResultSets=True,这是默认值的复制版本,修改DbConfiguration之前可以正常工作。

作为 sanity check,我尝试用同样的连接字符串创建SqlConnection并打开,完全没有问题:

using(SqlConnection xx =  new SqlConnection(connectionString))
{
    xx.Open();
}

我至今没找到服务器无法被识别的原因,还在排查中,如果有人能指出我的错误或遗漏,我会非常感激。

提前致谢,
Ondrej


内容的提问来源于stack exchange,提问作者Sarduk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 00:15:24