如何在 Asp.Net Core Mvc 5.0 中将 sql 数据库与 ado.net 连接?

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

我找不到我遗漏的地方。 我的代码是这样的;

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": "*"


}

最后我得到了这个错误;

处理请求时出现未处理的异常。 NullReferenceException:对象引用未设置到对象的实例。 Adonet_Sql.Models.users..ctor() 在 users.cs,第 14 行 Adonet_Sql.Models.users..ctor() 在 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.

您可能忘记在配置中添加连接字符串。 ConfigurationManager.ConnectionStrings["DefaultConnection"] returns null。它正在 App.config 中查找连接字符串。 Docs.

尝试阅读 并将 IConfigurationappsettings.json 结合使用。

ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

适用于 .net Core 3.0

在 5.0 中你需要使用;

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

private string connectionString = "Server=DESKTOP-1FOQ86Q ;Database=Users;Trusted_Connection=True;MultipleActiveResultSets=true"