Skip to content
Advertisement

How to connect sql Database with ado.net in Asp.Net Core Mvc 5.0?

I can not find where am i missing. my code like this ;

users.cs :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace Adonet_Sql.Models
{
public class users
{

    private string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
     public List<usersAccessLayer> getdata()
    {
        List<usersAccessLayer> li = new List<usersAccessLayer>();
        try
        {
            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand("test", conn);
            conn.Open();
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataReader rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                usersAccessLayer usr = new usersAccessLayer();
                usr.id = (string)rdr.GetValue(2);
                usr.name = rdr.GetString(0);
                usr.surname = rdr.GetString(1);
                li.Add(usr);
            }
     
        }
        catch (Exception)
        {

            throw;
        }

        return li;
    }
}

}

usersAccessLayer.cs ;

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Threading.Tasks;

      namespace Adonet_Sql.Models
      {
          public class usersAccessLayer
          {
    public string name { get; set; }
    public string surname { get; set; }
    public string id { get; set; }
}
      }

appsettings.json

    {
  "ConnectionStrings": {
"DefaultConnection": "Server=DESKTOP-1FOQ86Q; 
 Database=Users;Trusted_Connection=True;MultipleActiveResultSets=true""
 },
 "Logging": {
  "LogLevel": {
   "Default": "Information",
   "Microsoft": "Warning",
   "Microsoft.Hosting.Lifetime": "Information"
}
   },
 "AllowedHosts": "*"


}

And finally i got this error;

An unhandled exception occurred while processing the request. NullReferenceException: Object reference not set to an instance of an object. Adonet_Sql.Models.users..ctor() in users.cs, line 14 Adonet_Sql.Models.users..ctor() in users.cs

private string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
Adonet_Sql.Controllers.HomeController.Index() in HomeController.cs
sers obj = new users();
lambda_method1(Closure , object , object[] )
Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)

bla bla.

Advertisement

Answer

ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

is for .net Core 3.0

in 5.0 you need to use;

string connectionString = _configuration.GetConnectionString("DefaultConnection");

or

private string connectionString = "Server=DESKTOP-1FOQ86Q ;Database=Users;Trusted_Connection=True;MultipleActiveResultSets=true"
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement