我正在嘗試構建一個 .NET 6 Core MVC 應用程式,該應用程式顯示資料庫中的用戶記錄串列。但是我在嘗試打開連接時收到“連接字串屬性尚未初始化”錯誤。現在我正在嘗試在查詢字串中提供資料但收到此錯誤。
**DATA ACCESS LAYER**
using ABL_USER_DebitCard_Info.Models;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace ABL_USER_DebitCard_Info.Context
{
public class DebitCard_DAL
{
string connectionString = "Data Source = (localdb)\\MSSQLLocalDB; Initial Catalog = ABL_DebitCard_User_Info_DB";
public IEnumerable<Users> GetUserByCNIC(string? CNIC)
{
var debitcardList = new List<Users>();
using (SqlConnection conn = new SqlConnection())
{
SqlCommand cmd = new SqlCommand("ABL_GetUserByCNIC", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CNIC", CNIC);
conn.Open(); ---> 在這里出錯
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
var user = new Users();
user.Id = Convert.ToInt32(reader["ID"].ToString);
user.CNIC = reader["CNIC"].ToString();
user.UserName = reader["UserName"].ToString();
user.CardNumber = reader["CardNumber"].ToString();
user.CardStatus = reader["CardStatus"].ToString();
debitcardList.Add(user);
}
conn.Close();
}
return debitcardList;
}
}
}
**Controller**
using ABL_USER_DebitCard_Info.Context;
using ABL_USER_DebitCard_Info.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace ABL_USER_DebitCard_Info.Controllers
{
public class UsersController : Controller
{
DebitCard_DAL dbcontext = new DebitCard_DAL();
[HttpGet]
public ActionResult Details(string CNIC)
{
if(CNIC == null)
{
return NotFound();
}
else
{
List<Users> debitcardList = dbcontext.GetUserByCNIC(CNIC).ToList();
return View(debitcardList);
if(debitcardList.Count == 0)
{
return NotFound();
}
else
{
return View(debitcardList);
}
}
}
}
}
uj5u.com熱心網友回復:
您無需提供任何連接字串即可創建 SqlConnection。將連接字串傳遞給 SqlConnection 建構式
using (SqlConnection conn = new SqlConnection(connectionString ))
uj5u.com熱心網友回復:
有一個名為“ connectionString ”的變數很好,但不要忘記在需要時使用它:)
在創建 sql 連接的新實體時,您忘記放置它。
using (SqlConnection conn = new SqlConnection(connectionStringGoesHere))
uj5u.com熱心網友回復:
連接字串必須在 startup.cs 中提及使用它,或者您也可以使用 dapper 在 .net core 中運行查詢
using (SqlConnection conn = new SqlConnection(connectionString)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/458744.html
標籤:C# asp.net-mvc 数据库 asp.net-mvc-3
上一篇:超酷!!HTML5 Canvas 水流樣式 Loading 影片
下一篇:編譯器錯誤:未定義子或函式
