简体   繁体   中英

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. I have installed the MySQL.Data package and I use this code to build my connection:

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. 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). When I remove the MySQL.Data package, the MySqlConnection function becomes invalid (as would be expected).

Any idea what package to include and what function to use to establish the connection?

Any assistance is greatly appreciated. Thank you!

EDIT #1

I found an old stackoverflow post (I should have referenced it here but I closed the window) that talks about this very issue. 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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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