I can’t connect to my database using SqlConnection

189 Views Asked by At

I just try to connect to my database with SqlConnection, but I saw the error...

The point is I'm using System.Data.SqlClient, but it looks like it doesn't work somehow...

private string ConectionString = "Data Source=.;Initial Catalog=Contact_DB;Integrated Security=true";

public DataTable SelectAll()
{
    string query = "Select * From MyContacts";

    SqlConnection Connection = new SqlConnection(ConnectionString);
}

Also it shows this error:

Severity Code   Description   Project                                                                                                                                                                                                                                                                          File                                                                                             Line Suppression State
Error    CS1069 The type name 'SqlConnection' could not be found in the namespace 'System.Data.SqlClient'. This type has been forwarded to assembly 'System.Data.SqlClient, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' Consider adding a reference to that assembly.    MyCountacts    D:\Visual Studio Projects\C#\MyCountacts\MyCountacts\Repository\Services\MyContactsRepository.cs 28   Active

What can I do now?

1

There are 1 best solutions below

4
On

From your error message , it looks like you're using the System.Data.SqlClient namespace which has been deprecated in .NET Core 3.1 and later. In other words, .NET has pushed it to the curb in favor of Microsoft.Data.SqlClient. So what you're seeing is just .NET being a little finicky and saying, "Hey, I don't recognize this guy anymore."

To sort this out , you need to start using Microsoft.Data.SqlClient instead. This package should have all the functionality you're used to with System.Data.SqlClient, but it's the new and hip thing that .NET Core and .NET 5.0+ want you to use.

First thing's first , go to your package manager console and run this command to get the Microsoft.Data.SqlClient package:

Install-Package Microsoft.Data.SqlClient

After you've installed that , you need to change your using statement in your C# file from:

using System.Data.SqlClient;

to:

using Microsoft.Data.SqlClient;

Then you should be able to use SqlConnection just like before. So your connection string declaration will now look like this:

private string ConectionString = "Data Source=.;Initial Catalog=Contact_DB;Integrated Security=true";

public DataTable SelectAll()
{
    string query = "Select * From MyContacts";

    SqlConnection Connection = new SqlConnection(ConnectionString);
}