Created two tables: Members
and Contracts
.
Contracts
have a foreign key, the ID of Members
.
I also have two classes: Member
and Contract
.
My main static class Club
has an ArrayList
of Contract
, and each Contract
has a field Member
.
Now, in my Club
class I wanna populate in my ArrayList
every Contract
in the DB with the correct Member
field.
For some reason, this does not work: (This is a method Club
class)
public static void Populate()
{
string connStr = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Contribution;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
SqlConnection con = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("SELECT * FROM Contracts", con);
SqlDataReader dr;
try
{
con.Open();
dr = cmd.ExecuteReader();
while(dr.Read())
{
Member newMember = null;
int memberID = dr.GetInt32(dr.GetOrdinal("memberID"));
MessageBox.Show(memberID.ToString());
SqlCommand cmd2 = new SqlCommand("SELECT * FROM Members WHERE ID = @memberID", con);
cmd2.Parameters.AddWithValue("@memberID", memberID);
cmd2.ExecuteNonQuery();
SqlDataReader dr2;
dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
string name = dr2.GetString(dr2.GetOrdinal("name"));
DateTime birthDate = DateTime.ParseExact(dr2.GetString(dr2.GetOrdinal("birthDate")), "dd/MM/yyyy", null);
DateTime joinDate = DateTime.ParseExact(dr2.GetString(dr.GetOrdinal("joinDate")), "dd/MM/yyyy", null);
bool isPlaying = (dr2.GetInt32(dr2.GetOrdinal("isPlaying")) == 1 ? true : false);
newMember = new Member(name, birthDate, joinDate, isPlaying);
MessageBox.Show(name);
}
dr2.Close();
Club.AddContract(new Contract(newMember));
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
When testing, I do not get the expected results.
EDIT:
I get no results. I have methods that calculate the total Contribution and/or get the youngest member etc. All of those fields are either empty or null.
EDIT 2:
Switched up my code a bit: Used parameters, fixed some small mistakes. Still not working.