I have the following sql command with an Inner join:
SqlCommand cmd = new SqlCommand(@"SELECT c.comment_Id, c.date, c.comment, c.rating, a.registration_Date, a.username, a.email, a.profile_Image FROM News_comments c INNER JOIN News_accounts a ON c.account_Id=a.account_Id WHERE c.news_Id = @news_Id", conn);
cmd.Parameters.Add("news_Id", SqlDbType.Int).Value = news_Id;
conn.Open();
I want to put the values from a (News_accounts) in the object account that is in itself in the object newsComment which is located in a generic List, List newsComments.
I do that like this:
using (SqlDataReader reader = cmd.ExecuteReader()) {
while (reader.Read()) {
Comments newsComment = new Comments();
newsComment.comment_Id = int.Parse(reader["comment_Id"].ToString());
newsComment.date = DateTime.Parse(reader["date"].ToString());
newsComment.comment = reader["comment"].ToString();
newsComment.rating = int.Parse(reader["rating"].ToString());
newsComment.account.Registration_Date = DateTime.Parse(reader["registration_Date"].ToString());
newsComment.account.Username = reader["username"].ToString();
newsComment.account.Email = reader["email"].ToString();
newsComment.account.Profile_Image = reader["profile_Image"].ToString();
newsComments.Add(newsComment);
}
return newsComments;
}
Comments has a constructor:
public Comments(int comment_Id, DateTime date, string comment, int rating, Accounts account) {
this.comment_Id = comment_Id;
this.date = date;
this.comment = comment;
this.rating = rating;
this.account = account;
}
And Accounts account as well:
public Accounts(int account_Id, DateTime registration_Date, string email, string username, string profile_Image, string homepage, string about, bool admin) {
this.account_Id = account_Id;
this.registration_Date = registration_Date;
this.email = email;
this.profile_Image = profile_Image;
this.homepage = homepage;
this.about = about;
this.admin = admin;
}
Up until rating all goes well and the values are being put in the newsComment object, however, when it reaches the values that need to be put in the object account that is located in the object newsComment, it gives a NullReferenceException.
I know this means that it doesn’t have a value but I can’t seem to find why it has no value.
I’ve looked checked my Inner join with sql server 2008 query designer, and that works
so it’s got to be the object but I don’t see the problem.
please help me 🙂
greetings
newsComment.accountYou have to initialize that object before accessing its fields, properties, or methods. Something like this:… or you can do it from the constructor of the
Commentsclass, the one which takes no arguments.As a side note: maybe you should consider using an ORM, like LINQ to SQL or Entity Framework. It’s what they do.