简体   繁体   English

ASP.NET MVC C# 将代码从访问 mySQL 数据库更改为 MSSQL 数据库

[英]ASP.NET MVC C# change code from accessing a mySQL database to a MSSQL database

I have an application that I used to connect to a mySQL database.我有一个用于连接到 mySQL 数据库的应用程序。 I have installed the MySQL.Data package and I use this code to build my connection:我已经安装了 MySQL.Data package 并使用此代码来建立我的连接:

services.AddScoped<System.Data.IDbConnection>((s) =>
        {
            IDbConnection conn = new MySqlConnection(Configuration.GetConnectionString("databasename"));
            conn.Open();
            return conn;
        });

This works fine as I am able to read/write data from the database.这很好用,因为我能够从数据库中读取/写入数据。

Now, I need to have the same application access a MS SQL database.现在,我需要让同一个应用程序访问 MS SQL 数据库。 The tables are all the same and the fields on each table are the same as well.这些表都是相同的,每个表上的字段也相同。 I am having a hard time finding what I should change my code to (or what package I should include).我很难找到我应该将代码更改为什么(或者我应该包括什么 package)。 When I remove the MySQL.Data package, the MySqlConnection function becomes invalid (as would be expected).当我删除 MySQL.Data package 时,MySqlConnection function 变得无效(正如预期的那样)。

Any idea what package to include and what function to use to establish the connection?知道要包含什么 package 以及用来建立连接的 function 吗?

Any assistance is greatly appreciated.非常感谢任何帮助。 Thank you!谢谢!

EDIT #1编辑#1

I found an old stackoverflow post (I should have referenced it here but I closed the window) that talks about this very issue.我发现了一篇关于这个问题的旧 stackoverflow 帖子(我应该在这里引用它,但我关闭了窗口)。 The suggestion was to add建议是添加

using System.Data.SqlClient;

and then change the assignment code to然后将分配代码更改为

IDbConnection conn = new SqlConnection(Configuration.GetConnectionString("databasename"));

I made these changes and now I get this error within the code:我做了这些更改,现在我在代码中得到了这个错误:

在此处输入图像描述

Im at a loss as to how to resolve this.我不知道如何解决这个问题。 I verified that my project is in framework .NET core 3.1我验证我的项目在框架 .NET 核心 3.1 中

Not sure about size of your project and detailed requirements but I would suggest to use libraries like:不确定您的项目的大小和详细要求,但我建议使用以下库:

Entity Framework - no SQL knowledge needed, can connect to any Db technology, almost no code changes required when switching between Db providers实体框架 - 无需 SQL 知识,可以连接到任何 Db 技术,在 Db 提供者之间切换时几乎不需要更改代码

or或者

Dapper - fast lightweight also supports multiple Db providers but you need to write correct SQL commands yourself specific for each Db technology you use Dapper - 快速轻量级还支持多个 Db 提供程序,但您需要针对您使用的每种 Db 技术编写正确的 SQL 命令自己

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

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