I am currently making a controller to gather myself the data i need from a database. I am not allowed to use Entity Framework and i can't seem to find the reason my controller won't load the data from my SQL server... It is locally hosted on my computer and the connecntion string i am using is in the controller file itself.
Thanks in advance!
I have removed the data context from my controller because i can't share them
namespace ControllerFile.Controller
{
internal class ControllerFile
{
private static string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[""].ConnectionString;
public GroupModel GetModel(int Id)
{
string sqlQuery = " Query ";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(sqlQuery, con))
{
cmd.Parameters.AddWithValue("", );
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
try
{
Model user = new Model();
return user;
}
catch
{
MessageBox.Show("Error");
}
}
}
}
return new Model();
}
public void AddNewItem(Model, model)
{
string sqlQuery = " QUERY ";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(sqlQuery, con))
{
cmd.Parameters.AddWithValue("", model.id);
con.Open();
try
{
cmd.ExecuteNonQuery();
}
catch
{
MessageBox.Show("Error");
}
}
}
return;
}
}
}
The result should be a proper connection to my database where my listview loads the correct data. I have added a hardcoded variable with a filled model and that one did load into the listview. So we can rule that code out. It has to be in the controller.
CodePudding user response:
You're not using the data you get from the database anywhere in that code. You do this:
while (reader.Read())
but then you never actually get any data from the data reader. You just do this:
Model user = new Model();
return user;
so you're just returning a new, empty model, no matter what you get from the database. You need to actually get the appropriate data from the data reader and put it in the model, e.g.
Model user = new Model {SomeProperty = reader.GetString(reader.GetOrdinal("SomeColumn"))};
return user;