Hi Friends,
The data insertion in the sql database taking long time from the .net core application, I like to use Microsoft.Data.SqlClient
I used the following code
using (SqlConnection connection = new SqlConnection(@"Server=WIN-KOQSELR3408\SQLEXPRESS;Database=Test;User Id=sa;Password=9229"))
{
connection.Open();
}
The connection is not working ad it is throwing exception The type initializer for 'Microsoft.Data.SqlClient.SqlAuthenticationProviderManager' threw an exception
Please tell me how to resolve the issue?
Rahul ChauhanPosted Feb 12, 2025, 2:29 PM
1st you have to install package Microsoft.EntityFrameworkCore.SqlServer from Nuget Manager
After that mapped connection in appSettings.json
After that import namespace in your controller page
After that create connection object and bind, insert & update as you want.
public DataTable GetDataTable(string strQuery)
{
DataTable dt = new DataTable();
string connectionString = _configuration.GetConnectionString("DefaultConnection");
string strQuery = "select *from users where empid='user1' and pwd='abc@123' ";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter(strQuery, connection);
adapter.Fill(dt);
}
return dt;
}
prasanna pPosted Jan 30, 2025, 5:07 PM
Getting this error , The type initializer for 'Microsoft.Data.SqlClient.SqlConnection' threw an exception.
Rakesh KamathPosted Jan 30, 2025, 1:29 PM
If your application runs on the same machine as SQL Server, try:
string connectionString = @"Server=WIN-KOQSELR3408\SQLEXPRESS;Database=Test;Integrated Security=True;TrustServerCertificate=True;";
Rakesh KamathPosted Jan 30, 2025, 1:26 PM
Install -Package Microsoft.Data.SqlClient -Version 2.1.0 either by using commands or using Nuget Package update connection string as per yours.
using System;
using System.Data;
using Microsoft.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Server=your_server;Database=your_db;User Id=your_user;Password=your_password;";
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
Console.WriteLine("Connected to database!");
string query = "SELECT TOP 1 * FROM YourTable";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader[0]); // Print first column of the first row
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
}