I'm trying to build a .NET 6 Core MVC application that shows a list of user records from the database. But I'm getting the "The Connection String property has not been initialized" error when trying to open the connection. Right now I'm trying to give the data in query string but getting this error.
**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(); ---> GETTING ERROR HERE
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);
}
}
}
}
}
CodePudding user response:
You create the SqlConnection without providing any connection string.
Pass the connection string to the SqlConnection constructor
using (SqlConnection conn = new SqlConnection(connectionString ))
CodePudding user response:
It's good that you have a variable called "connectionString", but don't forget to use it when you need to :)
When making a new instance of your sql connection you forgot to put it.
using (SqlConnection conn = new SqlConnection(connectionStringGoesHere))
CodePudding user response:
connectionstring must mention in the startup.cs use this or you can use dapper also to run the query in .net core
using (SqlConnection conn = new SqlConnection(connectionString)