简体   繁体   English

使用命令 Update-Database 时无法连接到 DATABASE

[英]Unable to connect to DATABASE while using command Update-Database

So, let me explain the problem a bit.所以,让我稍微解释一下这个问题。 I have installed MYSQL server and created a new connection and a database MYSQL SERVER我已经安装了 MYSQL 服务器并创建了一个新连接和一个数据库MYSQL SERVER

And i can connect with no error: Connection no error我可以无错误地连接连接无错误

Then i used the "Server Explorer" menu in visual studio to connect to the same database and grab the connection string i will use.然后我使用 Visual Studio 中的“服务器资源管理器”菜单连接到同一个数据库并获取我将使用的连接字符串。 Server Explorer Wizard服务器资源管理器向导

Now i have this code:现在我有这个代码:

DataRepository.cs数据仓库.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TranscoopTrips.Data.Interfaces;

namespace TranscoopTrips.Data
{
    public class DataRepository<T> : IDataRepository<T> where T : class
    {
        private readonly DriverContext _context;

        public DataRepository(DriverContext context)
        {
            _context = context;
        }

        public void Add(T entity)
        {
            _context.Set<T>().Add(entity);
        }

        public void Update(T entity)
        {
            _context.Set<T>().Update(entity);
        }

        public void Delete(T entity)
        {
            _context.Set<T>().Remove(entity);
        }

        public async Task<T> SaveAsync(T entity)
        {
            await _context.SaveChangesAsync();
            return entity;
        }
    }
}

DriverContext.cs DriverContext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using ApplicazioneAutotrasporti.Model;

namespace TranscoopTrips.Data
{
    public class DriverContext : DbContext
    {
        public DriverContext (DbContextOptions<DriverContext> options)
            : base(options)
        {
        }

        public DbSet<ApplicazioneAutotrasporti.Model.Driver> Driver { get; set; }
    }
}

Driver.cs驱动程序

using ApplicazioneAutotrasporti.Model.interfaces;
using System.ComponentModel.DataAnnotations;

namespace ApplicazioneAutotrasporti.Model
{
    public class Driver : IDriver
    {
        [Key]
        public int id { get; set; }
        [Required]
        public string name { get; set; }
        [Required]
        public string surname { get; set; }
    }
}

appsettings.json appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "DriverContext": "server=127.0.0.1;user id=root;persistsecurityinfo=True;database=transcooptrips"
  },
  "AllowedHosts": "*"
}

Inside of Startup.cs Startup.cs 内部

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddDbContext<DriverContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DriverContext")));
            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
            services.AddScoped(typeof(IDataRepository<>), typeof(DataRepository<>));
        }

After the command: add-migration initialmigration a new file is created (XXXX_initialmigration.cs)在命令:add-migration initialmigration 之后创建一个新文件(XXXX_initialmigration.cs)

[using Microsoft.EntityFrameworkCore.Migrations;

    namespace TranscoopTrips.Migrations
    {
        public partial class initialmigration : Migration
        {
            protected override void Up(MigrationBuilder migrationBuilder)
            {
                migrationBuilder.CreateTable(
                    name: "Driver",
                    columns: table => new
                    {
                        id = table.Column<int>(nullable: false)
                            .Annotation("SqlServer:Identity", "1, 1"),
                        name = table.Column<string>(nullable: false),
                        surname = table.Column<string>(nullable: false)
                    },
                    constraints: table =>
                    {
                        table.PrimaryKey("PK_Driver", x => x.id);
                    });
            }

            protected override void Down(MigrationBuilder migrationBuilder)
            {
                migrationBuilder.DropTable(
                    name: "Driver");
            }
        }
    }][4]

So, now, i expect that using the command Update-Database a new table is created and all.所以,现在,我希望使用命令 Update-Database 创建一个新表。 But i recieve an exception Exception但我收到一个异常Exception

PM> update-database
Build started...
Build succeeded.
Microsoft.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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
 ---> System.ComponentModel.Win32Exception (2): The system cannot find the file specified.
   at Microsoft.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, DbConnectionPool pool, SqlAuthenticationProviderManager sqlAuthProviderManager)
   at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at Microsoft.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.<Exists>b__0(DateTime giveUp)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_0`2.<Execute>b__0(DbContext c, TState s)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation, Func`2 verifySucceeded)
   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.UpdateDatabaseImpl(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:00000000-0000-0000-0000-000000000000
Error Number:2,State:0,Class:20
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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

You're using the SqlServer initialisation code in the line:您在行中使用 SqlServer 初始化代码:

services.AddDbContext<DriverContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DriverContext")));

However, you have stated that the database you are using is MySQL , not SqlServer , which is a different product.但是,您已经声明您使用的数据库是MySQL ,而不是SqlServer ,后者是一个不同的产品。 Therefore changing the initialisation code to UseMySQL should solve the issue:因此将初始化代码更改为UseMySQL应该可以解决问题:

services.AddDbContext<DriverContext>(options => options.UseMySQL(Configuration.GetConnectionString("DriverContext")));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM