我的数据库不会更新,我的连接字符串有问题

My database won't update, something wrong with my connection string

我多年来一直试图解决这个问题,我尝试了不同的方法,但似乎没有任何效果。我已经成功完成了迁移,现在我的项目有了一个迁移文件。我正在尝试更新我的数据库,但每次尝试都会失败。

作为记录,我正在使用 Macbook 并为项目使用 Visual Code。我在命令行

中输入了这个

dotnet ef database update InitialCreatedotnet ef database update -c LoanContext DevelopmentBuild started...

Build succeeded.

info: Microsoft.EntityFrameworkCore.Infrastructure[10403] 



Entity Framework Core 2.2.6-servicing-10079 initialized 'LoanContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
"Logging": {

 "LogLevel": {

  "Default":"Warning"

  }

},

"AllowedHosts":"*",

"connectionStrings": {

 "DevConnection":"server=(local)\\\\sqlexpress;Database=LoanDB;Trusted_Connection=True;MultipleActiveResultSets=True"

}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.HttpsPolicy;

using Microsoft.AspNetCore.Mvc;

using Microsoft.EntityFrameworkCore;

using Microsoft.Extensions.Configuration;

using Microsoft.Extensions.DependencyInjection;

using Microsoft.Extensions.Logging;

using Microsoft.Extensions.Options;

using WebAPI.Models;



namespace WebAPI

{

  public class Startup

  {

    public Startup(IConfiguration configuration)

    {

      Configuration = configuration;

    }



    public IConfiguration Configuration { get; }



    // This method gets called by the runtime. Use this method to add services to the container.

    public void ConfigureServices(IServiceCollection services)

    {

      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);



      services.AddDbContext<LoanContext>(options =>

      options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));

    }



    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)

    {

      if (env.IsDevelopment())

      {

        app.UseDeveloperExceptionPage();

      }

      else

      {

        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.

        app.UseHsts();

      }



      app.UseHttpsRedirection();

      app.UseMvc();

    }

  }

}

我也试过这个:

dotnet ef database update InitialCreatedotnet ef database update -c LoanContext DevelopmentBuild started...

Build succeeded.

info: Microsoft.EntityFrameworkCore.Infrastructure[10403] 



Entity Framework Core 2.2.6-servicing-10079 initialized 'LoanContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
"Logging": {

 "LogLevel": {

  "Default":"Warning"

  }

},

"AllowedHosts":"*",

"connectionStrings": {

 "DevConnection":"server=(local)\\\\sqlexpress;Database=LoanDB;Trusted_Connection=True;MultipleActiveResultSets=True"

}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.HttpsPolicy;

using Microsoft.AspNetCore.Mvc;

using Microsoft.EntityFrameworkCore;

using Microsoft.Extensions.Configuration;

using Microsoft.Extensions.DependencyInjection;

using Microsoft.Extensions.Logging;

using Microsoft.Extensions.Options;

using WebAPI.Models;



namespace WebAPI

{

  public class Startup

  {

    public Startup(IConfiguration configuration)

    {

      Configuration = configuration;

    }



    public IConfiguration Configuration { get; }



    // This method gets called by the runtime. Use this method to add services to the container.

    public void ConfigureServices(IServiceCollection services)

    {

      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);



      services.AddDbContext<LoanContext>(options =>

      options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));

    }



    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)

    {

      if (env.IsDevelopment())

      {

        app.UseDeveloperExceptionPage();

      }

      else

      {

        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.

        app.UseHsts();

      }



      app.UseHttpsRedirection();

      app.UseMvc();

    }

  }

}

这是我输入上述

时在命令行中显示的内容

dotnet ef database update InitialCreatedotnet ef database update -c LoanContext DevelopmentBuild started...

Build succeeded.

info: Microsoft.EntityFrameworkCore.Infrastructure[10403] 



Entity Framework Core 2.2.6-servicing-10079 initialized 'LoanContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
"Logging": {

 "LogLevel": {

  "Default":"Warning"

  }

},

"AllowedHosts":"*",

"connectionStrings": {

 "DevConnection":"server=(local)\\\\sqlexpress;Database=LoanDB;Trusted_Connection=True;MultipleActiveResultSets=True"

}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.HttpsPolicy;

using Microsoft.AspNetCore.Mvc;

using Microsoft.EntityFrameworkCore;

using Microsoft.Extensions.Configuration;

using Microsoft.Extensions.DependencyInjection;

using Microsoft.Extensions.Logging;

using Microsoft.Extensions.Options;

using WebAPI.Models;



namespace WebAPI

{

  public class Startup

  {

    public Startup(IConfiguration configuration)

    {

      Configuration = configuration;

    }



    public IConfiguration Configuration { get; }



    // This method gets called by the runtime. Use this method to add services to the container.

    public void ConfigureServices(IServiceCollection services)

    {

      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);



      services.AddDbContext<LoanContext>(options =>

      options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));

    }



    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)

    {

      if (env.IsDevelopment())

      {

        app.UseDeveloperExceptionPage();

      }

      else

      {

        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.

        app.UseHsts();

      }



      app.UseHttpsRedirection();

      app.UseMvc();

    }

  }

}

System.Data.SqlClient.SqlException (0x80131904): 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: 25 - Connection string is not valid)

System.Net.Sockets.SocketException (0x80004005): Undefined error: 0

at System.Data.SqlClient.SNI.SSRP.GetPortByInstanceName(String browserHostName, String instanceName)

at System.Data.SqlClient.SNI.SNIProxy.CreateTcpHandle(DataSource details, Int64 timerExpire, Object callbackObject, Boolean parallel)

at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken)

at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)

at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)

at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)

at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)

at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)

at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)

at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)

at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)

at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)

at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry)

at System.Data.SqlClient.SqlConnection.Open()

at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(Boolean errorsExpected)

at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)

at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.c__DisplayClass18_0.b__0(DateTime giveUp)

at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.c__DisplayClass12_02.b__0(DbContext c, TState s)

at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func3 verifySucceeded)

at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, Func2 operation, Func2 verifySucceeded, TState state)

at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation)

at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists(Boolean retryOnNotExists)

at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists()

at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()

at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)

at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)

at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.c__DisplayClass0_1.<.ctor>b__0()

at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)</.ctor>

ClientConnectionId:00000000-0000-0000-0000-000000000000

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: 25 - Connection string is not valid)

这是我的 appsettings.json 文件

dotnet ef database update InitialCreatedotnet ef database update -c LoanContext DevelopmentBuild started...

Build succeeded.

info: Microsoft.EntityFrameworkCore.Infrastructure[10403] 



Entity Framework Core 2.2.6-servicing-10079 initialized 'LoanContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
"Logging": {

 "LogLevel": {

  "Default":"Warning"

  }

},

"AllowedHosts":"*",

"connectionStrings": {

 "DevConnection":"server=(local)\\\\sqlexpress;Database=LoanDB;Trusted_Connection=True;MultipleActiveResultSets=True"

}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.HttpsPolicy;

using Microsoft.AspNetCore.Mvc;

using Microsoft.EntityFrameworkCore;

using Microsoft.Extensions.Configuration;

using Microsoft.Extensions.DependencyInjection;

using Microsoft.Extensions.Logging;

using Microsoft.Extensions.Options;

using WebAPI.Models;



namespace WebAPI

{

  public class Startup

  {

    public Startup(IConfiguration configuration)

    {

      Configuration = configuration;

    }



    public IConfiguration Configuration { get; }



    // This method gets called by the runtime. Use this method to add services to the container.

    public void ConfigureServices(IServiceCollection services)

    {

      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);



      services.AddDbContext<LoanContext>(options =>

      options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));

    }



    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)

    {

      if (env.IsDevelopment())

      {

        app.UseDeveloperExceptionPage();

      }

      else

      {

        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.

        app.UseHsts();

      }



      app.UseHttpsRedirection();

      app.UseMvc();

    }

  }

}

我的 startup.cs 文件中的代码

dotnet ef database update InitialCreatedotnet ef database update -c LoanContext DevelopmentBuild started...

Build succeeded.

info: Microsoft.EntityFrameworkCore.Infrastructure[10403] 



Entity Framework Core 2.2.6-servicing-10079 initialized 'LoanContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
"Logging": {

 "LogLevel": {

  "Default":"Warning"

  }

},

"AllowedHosts":"*",

"connectionStrings": {

 "DevConnection":"server=(local)\\\\sqlexpress;Database=LoanDB;Trusted_Connection=True;MultipleActiveResultSets=True"

}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.HttpsPolicy;

using Microsoft.AspNetCore.Mvc;

using Microsoft.EntityFrameworkCore;

using Microsoft.Extensions.Configuration;

using Microsoft.Extensions.DependencyInjection;

using Microsoft.Extensions.Logging;

using Microsoft.Extensions.Options;

using WebAPI.Models;



namespace WebAPI

{

  public class Startup

  {

    public Startup(IConfiguration configuration)

    {

      Configuration = configuration;

    }



    public IConfiguration Configuration { get; }



    // This method gets called by the runtime. Use this method to add services to the container.

    public void ConfigureServices(IServiceCollection services)

    {

      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);



      services.AddDbContext<LoanContext>(options =>

      options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));

    }



    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)

    {

      if (env.IsDevelopment())

      {

        app.UseDeveloperExceptionPage();

      }

      else

      {

        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.

        app.UseHsts();

      }



      app.UseHttpsRedirection();

      app.UseMvc();

    }

  }

}

我也尝试通过此站点 https://www.connectionstrings.com/sql-server-2012/ 更改连接字符串。没有任何效果,对此的任何帮助将不胜感激。


您是否为 SQL Server 实例启用了 TCP?

启动 SQL Server 配置管理器并展开 SQL Server 网络配置和协议并检查值。以下示例显示 TCP/IP 已禁用 - 如果已禁用,则右键单击它并将其设置为启用并重新启动您的实例。

关于c#:我的数据库不会更新,我的连接字符串有问题


相关推荐

  • Spring部署设置openshift

    Springdeploymentsettingsopenshift我有一个问题让我抓狂了三天。我根据OpenShift帐户上的教程部署了spring-eap6-quickstart代码。我已配置调试选项,并且已将Eclipse工作区与OpehShift服务器同步-服务器上的一切工作正常,但在Eclipse中出现无法消除的错误。我有这个错误:cvc-complex-type.2.4.a:Invali…
    2025-04-161
  • 检查Java中正则表达式中模式的第n次出现

    CheckfornthoccurrenceofpatterninregularexpressioninJava本问题已经有最佳答案,请猛点这里访问。我想使用Java正则表达式检查输入字符串中特定模式的第n次出现。你能建议怎么做吗?这应该可以工作:MatchResultfindNthOccurance(intn,Patternp,CharSequencesrc){Matcherm=p.matcher…
    2025-04-161
  • 如何让 JTable 停留在已编辑的单元格上

    HowtohaveJTablestayingontheeditedcell如果有人编辑JTable的单元格内容并按Enter,则内容会被修改并且表格选择会移动到下一行。是否可以禁止JTable在单元格编辑后转到下一行?原因是我的程序使用ListSelectionListener在单元格选择上同步了其他一些小部件,并且我不想在编辑当前单元格后选择下一行。Enter的默认绑定是名为selectNext…
    2025-04-161
  • Weblogic 12c 部署

    Weblogic12cdeploy我正在尝试将我的应用程序从Tomcat迁移到Weblogic12.2.1.3.0。我能够毫无错误地部署应用程序,但我遇到了与持久性提供程序相关的运行时错误。这是堆栈跟踪:javax.validation.ValidationException:CalltoTraversableResolver.isReachable()threwanexceptionatorg.…
    2025-04-161
  • Resteasy Content-Type 默认值

    ResteasyContent-Typedefaults我正在使用Resteasy编写一个可以返回JSON和XML的应用程序,但可以选择默认为XML。这是我的方法:@GET@Path("/content")@Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})publicStringcontentListRequestXm…
    2025-04-161
  • 代码不会停止运行,在 Java 中

    thecodedoesn'tstoprunning,inJava我正在用Java解决项目Euler中的问题10,即"Thesumoftheprimesbelow10is2+3+5+7=17.Findthesumofalltheprimesbelowtwomillion."我的代码是packageprojecteuler_1;importjava.math.BigInteger;importjava…
    2025-04-161
  • Out of memory java heap space

    Outofmemoryjavaheapspace我正在尝试将大量文件从服务器发送到多个客户端。当我尝试发送大小为700mb的文件时,它显示了"OutOfMemoryjavaheapspace"错误。我正在使用Netbeans7.1.2版本。我还在属性中尝试了VMoption。但仍然发生同样的错误。我认为阅读整个文件存在一些问题。下面的代码最多可用于300mb。请给我一些建议。提前致谢publicc…
    2025-04-161
  • Log4j 记录到共享日志文件

    Log4jLoggingtoaSharedLogFile有没有办法将log4j日志记录事件写入也被其他应用程序写入的日志文件。其他应用程序可以是非Java应用程序。有什么缺点?锁定问题?格式化?Log4j有一个SocketAppender,它将向服务发送事件,您可以自己实现或使用与Log4j捆绑的简单实现。它还支持syslogd和Windows事件日志,这对于尝试将日志输出与来自非Java应用程序…
    2025-04-161