2011-11-20 111 views
0

我有一個內以下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(); 

我想把值從一個(News_accounts)在對象賬戶那本身就是對象新聞評論它位於一個通用名單,名單新聞評論。 我是這樣做的:

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

直到評級一切順利的話,其值是放入新聞評論對象,但是,當它達到需要放入對象的值時ac計數即位於對象新聞評論,它給出了一個NullReferenceException。 我知道這意味着它沒有價值,但我似乎無法找到爲什麼它沒有價值。

我看過檢查我的內部加入與SQL Server 2008查詢設計器,並且工作 所以它必須是對象,但我沒有看到問題。

請幫我:)

問候

回答

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。這是他們做的。

+0

這是一個學校項目,對於這個我們不允許使用LINQ呢;) –

+0

這就是它當然,我怎麼可能錯過了:facepalm –

1

您還沒有實例化您的帳戶對象,因此它是空

+0

你的意思是我需要把: newsComment.account = new Accounts(); 之後: 評論newsComment = new Comments(); ?編輯: 沒錯,就是這樣。 –

+0

是的,如果它有一個默認構造器 –

相關問題