实体框架 6 连接字符串混淆

时间:2021-05-27 14:40:29

标签: c# entity-framework asp.net-core connection-string

我有一个有趣的问题。

在我的上下文中,如果我在 base 方法中调用连接字符串本身,则没有问题。它工作正常。但是,如果我尝试从任何配置文件中获取连接字符串,Ef 就会感到困惑。 这是我的连接字符串: enter image description here 这是我的上下文: enter image description here 当我尝试调用它时,结果如下:enter image description here 实体框架将初始目录的名称更改为连接字符串的名称。我通过使它们相同来克服这种情况。但不幸的是,在生产服务器中出了点问题,它甚至没有初始化数据库。当我放置连接字符串本身时,它工作得很好。 这是生产服务器上的例外:

Connection ID "18014398515387564057", Request ID "8000001c-0001-fa00-b63f-84710c7967bb": An unhandled exception was thrown by the application.
      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: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)
       ---> System.ComponentModel.Win32Exception (2): The system cannot find the file specified.
         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, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
         at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
         at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
         at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
         at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
         at System.Data.SqlClient.SqlConnection.Open()
         at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<>c.<Open>b__13_0(DbConnection t, DbConnectionInterceptionContext c)
         at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
         at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
         at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass60_0.<UsingConnection>b__0()
         at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass2_0.<Execute>b__0()
         at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
         at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
         at System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action`1 act)
         at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act)
         at System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable`1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript)
         at System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
         at System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
         at System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase()
         at System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection)
         at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
         at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
         at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
         at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update()
         at System.Data.Entity.MigrateDatabaseToLatestVersion`2.InitializeDatabase(TContext context)
         at System.Data.Entity.Internal.InternalContext.<>c__DisplayClass66_0`1.<CreateInitializationAction>b__0()
         at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
         at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
         at System.Data.Entity.Internal.LazyInternalContext.<>c.<InitializeDatabase>b__58_0(InternalContext c)
         at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
         at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
         at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
         at System.Data.Entity.Internal.InternalContext.Initialize()
         at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
         at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
         at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
         at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
         at System.Linq.Queryable.Join[TOuter,TInner,TKey,TResult](IQueryable`1 outer, IEnumerable`1 inner, Expression`1 outerKeySelector, Expression`1 innerKeySelector, Expression`1 resultSelector)
         at Mbis.Dispatcher.DataAccess.Concrete.EntityFramework.EfEnvelopeDal.GetEnvelopesWithFirstDocument(Expression`1 filter) in D:\MyProjects\MbisDispatcher\Mbis.Dispatcher\Mbis.Dispatcher.DataAccess\Concrete\EntityFramework\EfEnvelopeDal.cs:line 20
         at Mbis.Dispatcher.Business.Concrete.EnvelopeManager.GetEnvelopeDetailList() in D:\MyProjects\MbisDispatcher\Mbis.Dispatcher\Mbis.Dispatcher.Business\Concrete\EnvelopeManager.cs:line 123
         at Mbis.Dispatcher.WebApi.Controllers.EnvelopeController.GetList() in D:\MyProjects\MbisDispatcher\Mbis.Dispatcher\Mbis.Dispatcher.WebApi\Controllers\EnvelopeController.cs:line 20
         at lambda_method2(Closure , Object , Object[] )
         at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
         at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
         at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContextOfT`1.ProcessRequestAsync()

1 个答案:

答案 0 :(得分:0)

首先,我尝试使用您的代码通过 nameOrConnectionString 属性设置连接字符串,但它会显示以下提示:

enter image description here

修改如下代码后,一切正常,你可以试试。

在 DbContext 构造函数中添加字符串参数:

public class SchoolContext : DbContext
{
    public SchoolContext(string connString) : base(connString)
    {
    }

在 Startup.ConfigureServices 方法中,使用连接字符串注册 DBContext。

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddScoped<SchoolContext>(_ => 
            new SchoolContext(Configuration.GetConnectionString("DefaultConnection")));
    }

appsetting.json 文件中的连接字符串如下:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=EF6MVCCore;Trusted_Connection=True;MultipleActiveResultSets=true"
  },

调试代码时,dbcontext连接字符串如下:

enter image description here

更多详细信息,可以参考ASP.NET Core and Entity Framework 6

相关问题