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

问题描述 投票:0回答:2

我有一个简单的 Web 应用程序,它是从 .NET 5 和 EF Core 5 版本上的 Visual Studio 生成的,唯一添加的是 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();
        }
    }
}

获取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 上不起作用。EF Core 7 中有关连接到服务器(位于本地计算机上并且具有别名本地)的内容是否发生了变化?

.net entity-framework-core asp.net-core-webapi .net-7.0 ef-core-7.0
2个回答
2
投票

更新

我仔细检查了错误消息,可能还有其他原因导致该问题。请检查链接进行配置。我们不需要 ApexSQL 工具,只需按照文档配置 sql server 即可。

如何使用 ApexSQL 工具配置远程访问并连接到远程 SQL Server 实例


上一个

根据错误信息,您可以按照我的步骤获取正确的连接字符串。

正确的格式应如下所示:

Server=(localdb)\\mssqllocaldb;Database=aspnet-Core6MVCSignalR-64406da8-b697-43cb-9c46-aaa950b705b1;Trusted_Connection=True;MultipleActiveResultSets=true

步骤

  1. 在vs2022(或其他版本)中打开sql server对象资源管理器

  2. 查找数据库(SamuraiApp)

  3. 找到连接字符串。


0
投票

请在nuget包中安装Microsoft.EntityFrameworkCore.SqlServer

© www.soinside.com 2019 - 2024. All rights reserved.