将Inner join中的值放入对象中的对象中

时间:2011-11-20 12:05:14

标签: c# asp.net inner-join generic-list

我有以下带有内连接的sql命令:

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();

我想将 a (News_accounts)中的值放在对象帐户中,该对象本身位于对象 newsComment 中在通用列表中,列表newsComments 。 我这样做:

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;
}

评论有一个构造函数:

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;
}

还有帐户帐户:

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;
}

直到评级一切顺利并且值被放入 newsComment 对象中,然而,当它达到需要放入对象帐户的值时它位于对象 newsComment 中,它给出了NullReferenceException。 我知道这意味着它没有价值,但我似乎无法找到它没有价值的原因。

我看起来已经检查了我的内部联接与sql server 2008查询设计器,这是有效的 所以它必须是对象,但我没有看到问题。

请帮帮我:)。

问候

2 个答案:

答案 0 :(得分:1)

您没有实例化您的帐户对象,因此它为空

答案 1 :(得分:1)

newsComment.account您必须在访问其字段,属性或方法之前初始化该对象。像这样:

newsComment.account = new Account();
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();

...或者您可以从Comments类的构造函数中执行此操作,该类不带参数。

作为旁注:也许你应该考虑使用ORM,比如LINQ to SQL或Entity Framework。这就是他们所做的。