I'm kind a new on c#. I have a problem with to store the className to list since i need to display all the class that teacher taught. On result, it turns out just the last class teacher taught. I did use join table between teacher and classes.
Model
public class Teacher
{
public int teacherId { get; set; }
public string teacherfName { get; set; }
public string teacherlName { get; set; }
public string className { get; set; }
public int classId { get; set; }
}
Controller
public Teacher FindTeacher(int id)
{
Teacher newTeacher = new Teacher();
MySqlConnection Conn = school.AccessDatabase();
Conn.Open();
MySqlCommand cmd = Conn.CreateCommand();
//SQL QUERY
cmd.CommandText = "Select * from teachers left join classes on teachers.teacherid=classes.teacherid where teachers.teacherid = " + id;
//Gather Result Set of Query into a variable
MySqlDataReader ResultSet = cmd.ExecuteReader();
while (ResultSet.Read())
{
int teacherId = (int)ResultSet["teacherId"];
string teacherfName=ResultSet["teacherfname"].ToString();
string teacherlName=ResultSet["teacherlname"].ToString();
newTeacher.teacherId = teacherId;
newTeacher.teacherFName = teacherFName;
newTeacher.teacherLName = teacherLName;
newTeacher.className = className;
newTeacher.classId = (int)ResultSet["classid"];
}
return newTeacher;
}
Your only returning one teacher if you want all the teachers your code should be:
public IEnumerable<Teacher> FindTeacher(int id)
{
//Lise here
List<Teacher> teachers = new List<Teacher>();
//note the using
using MySqlConnection Conn = school.AccessDatabase();
Conn.Open();
//note the using
using MySqlCommand cmd = Conn.CreateCommand();
//SQL QUERY
cmd.CommandText = "Select * from teachers left join classes on teachers.teacherid=classes.teacherid where teachers.teacherid = " + id;
//Gather Result Set of Query into a variable
MySqlDataReader ResultSet = cmd.ExecuteReader();
while (ResultSet.Read())
{
//new teacher in the loop
Teacher newTeacher = new Teacher();
int teacherId = (int)ResultSet["teacherId"];
string teacherfName=ResultSet["teacherfname"].ToString();
string teacherlName=ResultSet["teacherlname"].ToString();
newTeacher.teacherId = teacherId;
newTeacher.teacherFName = teacherFName;
newTeacher.teacherLName = teacherLName;
newTeacher.className = className;
newTeacher.classId = (int)ResultSet["classid"];
//add to the collection
teachers.Add(newTeacher);
}
//return the collection
return teachers;
}
If also added using statements. These are important to prevent memory leaks
Modify Teacher Class to be able to carry List of TeacherClass that correspond to one teacher:
Define New Class TeacherClass to Carry a TeacherClass Data
public class TeacherClass
{
public string Name { get; set; }
public int Id { get; set; }
}
Modify Teacher Class To have a List Of TeacherClass
public class Teacher
{
public int teacherId { get; set; }
public string teacherfName { get; set; }
public string teacherlName { get; set; }
public List<TeacherClass> classes { get; set; } = new List<TeacherClass>();
}
Then get your function to set this TeacherClass List in a loop:
public Teacher FindTeacher(int id)
{
Teacher newTeacher = new Teacher();
//note the using
using MySqlConnection Conn = school.AccessDatabase();
Conn.Open();
//note the using
using MySqlCommand cmd = Conn.CreateCommand();
//SQL QUERY
cmd.CommandText = "Select * from teachers left join classes on teachers.teacherid=classes.teacherid where teachers.teacherid = " + id;
//Gather Result Set of Query into a variable
MySqlDataReader ResultSet = cmd.ExecuteReader();
// Check if any rows retrieved
if (reader.HasRows)
{
// Iterate Over Rows
while (ResultSet.Read())
{
// Set Teacher Data Just Once
if(newTeacher.teacherId == 0){
newTeacher.teacherId = (int)ResultSet["teacherId"];;
newTeacher.teacherFName = ResultSet["teacherfname"].ToString();
newTeacher.teacherLName = ResultSet["teacherlname"].ToString();
}
// Add new TeacherClass data for this teacher
newTeacher.classes.Add(
new TeacherClass(){
Name = className, // className Check this variable as it is not declared
Id = (int)ResultSet["classid"]
});
}
}
return newTeacher;
}
Related
How to save the select data below into an array.
SqlConnection conConexao1 = clsdb.AbreBanco();
SqlCommand cmd1 = new SqlCommand("select id, tamplete1, tamplete2 from usuarios ", conConexao1);
SqlDataReader dr1 = cmd1.ExecuteReader();
if (dr1.HasRows == true)
{
if (dr1.Read())
{
id = int.Parse(dr1[0].ToString());
templete1 = (dr1[1].ToString());
templete2 = (dr1[2].ToString());
}
}
I have already tried using foreach, but always passes the last table data.
As a collection, List provide better flexibility than array.
The collection should be created outside the loop and the element should be added inside the loop.
List<Usuarios> list = new List<Usuarios>();
using (SqlConnection conConexao1 = clsdb.AbreBanco())
using (SqlCommand cmd1 = new SqlCommand(
"select id, tamplete1, tamplete2 from usuarios ", conConexao1))
using (SqlDataReader dr1 = cmd1.ExecuteReader())
{
while (dr1.Read())
{
list.Add(new Usuarios
{
Id = dr1.GetInt32(0),
Templete1 = dr1[1].ToString(),
Templete2 = dr1[2].ToString()
});
}
}
The class to imitate your data structure
public class Usuarios
{
public int Id { get; set; }
public string Templete1 { get; set; }
public string Templete2 { get; set; }
}
if for some reason, you have to use an array as collection
Usuarios[] array = list.ToArray();
I am using Sqlite with C#. When i run the query in Sqlite browser it returns the correct data but when i run the same query from C# code it does not return data. My C# code is:
foreach (var group in groups)
{
var edgeDataWithGroupCmd = EdgeDatabase._connection.CreateCommand(#"SELECT ad.Id, ad.Name, adType.Id, adType.Name, h.Data, chart.URL
from
tblAdapter ad JOIN
tblAdapterType adType ON ad.AdapterTypeId = adType.Id JOIN
tblHealth h ON ad.HealthId = h.Id JOIN
tblCharts chart ON ad.ChartId = chart.Id
WHERE ad.GroupId = " + group.Id);
List<EdgeData> edgeDatas = edgeDataWithGroupCmd.ExecuteQuery<EdgeData>();
}
When i run this query in C#, query does return a list of "EdgeData" but all the values are set to there default and not the exact data from database. I am using sqlite-net.
EdgeData is a custom class:
public class EdgeData
{
public int AdapterId { get; set; }
public string AdapterName { get; set; }
public int AdapterTypeId { get; set; }
public string AdapterTypeName { get; set; }
public bool IsConnected { get; set; }
public int MaxRefreshRate { get; set; }
public int AchievedRefreshRate { get; set; }
public string ChartLink { get; set; }
}
//get one instance, and use function in logic/business layer to create list
//or rebuild function to return a list<EdgeData>
public EdgeData GetEdgeData(int groupID)
{
connection.open();
EdgeData edgeData;
StringBuilder sb = new StringBuilder();
sb.Append("SELECT ad.Id, ad.Name, adType.Id, adType.Name, h.Data, chart.URL
from
tblAdapter ad JOIN
tblAdapterType adType ON ad.AdapterTypeId = adType.Id JOIN
tblHealth h ON ad.HealthId = h.Id JOIN
tblCharts chart ON ad.ChartId = chart.Id
WHERE ad.GroupId = #GroupId");
SqlDataReader data;
String sql = sb.ToString();
//Use sql injection instead of "+"
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.AddWithValue("#GroupId", groupID);
data = cmd.ExecuteReader();
}
while (data.Read())
{
int AdapterId = (int)data["ad.Id"]
string AdapterName = (string)data["ad.Name"]
int AdapterTypeId = ...
string AdapterTypeName = ...
bool IsConnected = ...
int MaxRefreshRate = ...
int AchievedRefreshRate = ..
string ChartLink = ..
edgeData = new EdgeData(AdapterId, AdapterName, etc...);
}
connection.Close();
return edgeData;
}
I am trying to use a web service to retrieve data for more than one column. The code below works fine :
public string GetCustomerNameWithIDNumber(string id_number)
{
string fullname ="";
string id_type = "";
string id_number = "";
string dob = "";
using (SqlConnection cn = new SqlConnection(constring))
{
cn.Open();
string q = "select fullname, id_type, id_number, date_ofbirth from account_info where id_number = #id_number";
using (SqlCommand cmd = new SqlCommand(q, cn))
{
cmd.Parameters.AddWithValue("#id_number", id_number);
using (SqlDataReader rd = cmd.ExecuteReader())
{
while (rd.Read())
{
fullname = rd["fullname"].ToString();
id_type = rd["id_type"].ToString();
id_number = rd["id_number"].ToString();
dob = rd["date_ofbirth"].ToString();
bvn2 = rd["bvn"].ToString();
}
}
return fullname;
}
}
}
Which just gets the Full name alone, now suppose i want to get for more than just one database column, how do I go about it?
You will want to return a class. Here is a simple class I wrote to hold this data:
class Customer {
public string FullName { get; set; }
public string IdType { get; set; }
public string IdNumber { get; set; }
public string DateOfBirth { get; set; }
public string Bvn { get; set; }
}
Then this method returns that customer object:
public Customer GetCustomerNameWithIDNumber(string id_number) {
using (SqlConnection cn = new SqlConnection(constring)) {
cn.Open();
string q = "select fullname,id_type,id_number,date_ofbirth from account_info where id_number =#id_number";
using (SqlCommand cmd = new SqlCommand(q, cn)) {
cmd.Parameters.AddWithValue("#id_number", id_number);
using (SqlDataReader rd = cmd.ExecuteReader()) {
while (rd.Read()) {
return new Customer {
FullName = rd["fullname"].ToString(),
IdType= rd["id_type"].ToString(),
IdNumber = rd["id_number"].ToString(),
DateOfBirth = rd["date_ofbirth"].ToString(),
Bvn = rd["bvn"].ToString()
};
}
}
}
}
}
This code will return the first customer in the database matching the id_number
I am creating my first project using asp.net MVC - I have successfully connected to the database and displayed the information on the index page. My question is how do I get more than one query result on the one index page
for e.g
SELECT student ID,first name,surname FROM STUDENT Notes WHERE student ID = 7
Do I need to create new controllers/models for each query or need to add to the current and if I add to the current how would I do it? Below is the code I currently have in my controller.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
//int sNumber = 1;
List<CustomerModel> customers = new List<CustomerModel>();
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "SELECT title, `first name`, surname FROM `STUDENT REGISTER`";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(new CustomerModel
{
// CustomerId = Convert.ToInt32(sdr["Student Number"]),
Title = sdr["title"].ToString(),
Name = sdr["first name"].ToString(),
Surname = sdr["surname"].ToString()
});
}
}
con.Close();
}
}
return View(customers);
}
Create a view model with two result set for e.g. Student and Marks
public class Result
{
public Student Student { get; set; }
public Marks Marks { get; set; }
}
Load/Construct this Result view model in controller /service with appropriate data and pass this view model to view.
I hope this helps!
You have to create a new class with all the properties you want to display in your View.
Example:
public class StudentModel {
public int Id { get; set; }
public string Title { get; set; }
public string Name { get; set; }
public strign Surname { get; set; }
}
public class MarkModel {
public int Id { get; set; }
public int StudentId { get; set; }
public int SubjectId { get; set; }
public int Mark { get; set; }
}
public class ResultModel
{
public StudentModel Student { get; set; }
public List<MarkModel> Marks { get; set; }
}
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
//int sNumber = 1;
var model= new ResultModel{
Student = new StudentModel(),
Marks = new List<MarkModel>();
}
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string queryStudent = "SELECT id, title, `first name`, surname FROM `STUDENT` WHERE Id=1";
using (MySqlCommand cmd = new MySqlCommand(queryStudent))
{
cmd.Connection = con;
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
model.student.Id = Convert.ToInt32(sdr["id"]),
model.student.Title = sdr["title"].ToString(),
model.student.Name = sdr["first name"].ToString(),
model.student.Surname = sdr["surname"].ToString()
}
}
}
string queryMarks = "SELECT Id, `StudentId`, StudentId,Mark FROM `MARK` WHERE StudentId=1";
using (MySqlCommand cmd = new MySqlCommand(queryMarks))
{
cmd.Connection = con;
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
model.Marks.Add(new MarkModel
{
Id = Convert.ToInt32(sdr["Id"]),
StudentId = Convert.ToInt32(sdr["StudentId"]),
StudentId = Convert.ToInt32(sdr["StudentId"]),
Mark = Convert.ToInt32(sdr["Mark"]),
});
}
}
}
}
return View(model);
}
You should create a new ViewModel class with all the properties you want to display in your View. Then you model your View after it.
From the properties you provided so far, the class should look like this:
public class StudentViewModel {
public int Id { get; set; }
public string Title { get; set; }
public string Name { get; set; }
public strign Surname { get; set; }
}
Then you do the value x property assignment
string query = "SELECT title, `first name`, surname FROM `STUDENT REGISTER`";
List<StudentViewModel> model = new List<StudentViewModel>();
using (MySqlCommand cmd = new MySqlCommand(query)) {
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
model.Add(new StudentViewModel
{
Id = Convert.ToInt32(sdr["StudentNumber"]),
Title = Convert.ToString(sdr["title"]),
Name = Convert.ToString(sdr["first name"]),
Surname = Convert.ToString(sdr["surname"])
});
}
}
con.Close();
}
return View(model);
Consider a Winforms app connecting to a SQL Server 2008 database and running a SQL SELECT statement:
string myConnectionString = "Provider=SQLOLEDB;Data Source=hermes;Initial Catalog=qcvaluestest;Integrated Security=SSPI;";
string mySelectQuery = "SELECT top 500 name, finalconc from qvalues where rowid between 0 and 25000;";
OleDbConnection myConnection = new OleDbConnection(myConnectionString);
OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection);
myCommand.Connection.Open();
OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
How can you read the results of the query into a list?
Assume you have defined a class that is something like
class MyData
{
public string Name {get; set;}
public int FinalConc {get; set;} // or whatever the type should be
}
You would iterate through the results of your query to load a list.
List<MyData> list = new List<MyData>();
while (myReader.Read())
{
MyData data = new MyData();
data.Name = (string)myReader["name"];
data.FinalConc = (int)myReader["finalconc"]; // or whatever the type should be
list.Add(data);
}
// work with the list
If you just need one of the given fields, you can forego the class definition and simply have a List<T>, where T is the type of whatever field you want to hold.
You can try something as (adapt it for your convenience):
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
List<Person> dbItems = new List<Person>();
while(myReader.Read())
{
Person objPerson = new Person();
objPerson.Name = Convert.ToString(myReader["Name"]);
objPerson.Age = Convert.ToInt32(myReader["Age"]);
dbItems.Add(objPerson);
}
List of what? Do you have a class setup that has properties for name and finalconc? Saying you do, and it looks like this:
public class QueryResult
{
public string Name { get; set; }
//not sure what finalconc type would be, so here just using string
public string FinalConc { get; set; }
}
Then you would do something like this:
var queryResults = new List<QueryResult>();
using(var myReader = myCommand.ExecuteReader())
{
while(myReader.Read())
{
queryResults.Add(new QueryResult
{
Name = myReader.GetString(myReader.GetOrdinal("name")),
FinalConc = myReader.GetString(myReader.GetOrdinal("finalconc"))
});
}
}