将数据库连接到 .net 核心 MVC 项目

Connecting database to .net core MVC project

这是我第一次使用 .NET core 2.2 和 MySQL workbench ,

我正在尝试建立一个非常基础的网站。

我遵循了以下 Microsoft 教程

https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/working-with-sql?view=aspnetcore-2.2&tabs=visual-studio

添加 Scaffolded 项目后,我按照说明打开 NuGet 包管理器并在 cli 中执行了这些命令:

Add-Migration Initial Update-Database

Update-Database 命令引发了以下错误:

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)

我正在使用 Bluehost(共享主机)服务器,我修改了权限以便我可以远程连接到数据库(实际上我是通过 MySQL workbench 连接的)

我尝试将 ConnectionString 更改为以下内容:

"ConnectionStrings": 
{
    "Piano3Context": "Server=162.241.*.*;Database=PianoDB;User Id=omyUsrName;password=myPass;Trusted_Connection=True;MultipleActiveResultSets=true;"
}

但我收到同样的错误。

如果有任何其他代码有帮助,请注意,我会post。

您提到的教程使用的是 SQL-Server。要连接到 MySql 服务器,您需要不同的数据库提供程序。您可以为 Mysql 安装 Pomelo.EntityFrameworkCore.MySql nuget 包。请参阅 Microsoft 文档中的 providers page

之后,您需要按照 mysql providers project page 中所述将教程中的 options.UseSqlServer 更改为 options.UseMySql

此外,这是MySQL选项的设置方法,您可以将配置字符串移动到Configuration并使用GetConnectionString方法。

services.AddDbContextPool<MvcMovieContext>(
            options => options.UseMySql("Server=localhost;Database=ef;User=root;Password=123456;", 
                mySqlOptions =>
                {
                    mySqlOptions.ServerVersion(new Version(5, 7, 17), ServerType.MySql); // replace with your Server Version and Type
                }
        ));

我被@philipp-grathwohl 打败了,你需要使用 MySql 并像他的回答说的那样在你的启动中配置它。

您可以改用此命令,在更改启动并添加 nuget 包后,它会在一个命令中搭建 DBContext 并生成 EF 模型和上下文 Pomelo.EntityFrameworkCore.MySql:

Scaffold-DbContext "Server=<ip>;Initial Catalog=PianoDB;Persist Security Info=False;User ID=<username>;Password=<password>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" Pomelo.EntityFrameworkCore.MySql -OutputDir Models -context Piano3Context -force

如果最后一条命令出现任何错误,请告诉我。