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

使用EF Core 7连接本地SQL Server时出现连接失败问题

EF Core 7 使用(local)连接SQL Server失败,低版本EF Core正常

我有一个通过Visual Studio基于.NET 5和EF Core 5生成的简单Web应用,仅添加了WebDbContext和SQL查询以验证数据库连接是否正常。

WebDbContext代码

namespace WebApplication1.Data
{
    public class WebDbContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string connectionString = "Data Source = (local); Initial Catalog = SamuraiApp; Integrated Security = True;"; 
                                                                                                                          //Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MyWorldDB;Integrated Security=True;Connect Timeout=30

            optionsBuilder.UseSqlServer(connectionString)
                .LogTo(Console.WriteLine,
                        new[] {
                            DbLoggerCategory.Database.Command.Name,
                        }
                        , LogLevel.Information
                        )
                .EnableSensitiveDataLogging();
        }
    }
}

Get API代码

[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
    WebDbContext dbContext = new WebDbContext();
    var res = dbContext.Database.ExecuteSqlInterpolated($"UPDATE battles SET Name = Name");

    Console.WriteLine("Number of rows: " + res);

    var rng = new Random();
    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = rng.Next(-20, 55),
        Summary = Summaries[rng.Next(Summaries.Length)]
    })
    .ToArray();
}

环境与报错

该应用在.NET 5+EF Core 5、.NET 6+EF Core 6、.NET 7+EF Core 6环境下均可正常连接数据库,但切换到.NET 7+EF Core 7时无法连接,报错信息如下:

Microsoft.Data.SqlClient.SqlException: '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: TCP Provider, error: 0 - No such host is known.)'

未修改任何代码,数据库位置也未变动,低版本EF Core均可正常连接,请问EF Core 7在连接本地别名(local)的SQL Server时是否有变更?


解答

EF Core 7本身并未直接修改(local)别名的解析逻辑,但它依赖的Microsoft.Data.SqlClient版本升级(EF Core 7默认使用Microsoft.Data.SqlClient 5.x系列)带来了连接字符串解析的变化。

旧版本SqlClient中,(local)会优先尝试命名管道连接,新版SqlClient对本地实例的解析逻辑调整,可能导致(local)无法正确映射到本地SQL Server实例,转而尝试TCP连接时找不到主机。

解决方法

  • 替换连接字符串中的(local)为具体实例标识:比如localhost、.(点号),或者你的SQL Server实例全名(如DESKTOP-XXX\SQLEXPRESS)
  • 如果使用LocalDB,明确指定实例名(localdb)\MSSQLLocalDB(对应代码中注释的连接字符串)
  • 强制指定连接协议:在连接字符串中添加Network Library=dbnmpntw强制使用命名管道,或Network Library=dbmssocn强制使用TCP连接,验证哪种方式能正常连接

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 10:43:13