I’m trying to populate a dataset with records from a MySql database, then looping through each record of the table in the dataset, creating and populating a custom data object each pass through the loop, and finally retuning a list of the data objects created.
The problem I’m having is that I get an error when trying to create each data object:
ERROR:
System.InvalidCastException: Specified cast is not valid.
The error highlights this line of code: var newsRelease = new NewsRelease
I suspect one of two issues:
1) the object cannot be created due to formatting issues with MySql DateTime data types vs. C# DateTime data types/
2) The select query is not actually returning anything and thus there is nothing to populate the NewsRelease object with.
I have tried testing for both issues but can’t seem to determine if either is actually the issue. Any insight as to what my problem is and how to fix it is greatly appreciated.
public List<NewsRelease> SELECT()
{
MySqlConnection connection = new MySqlConnection(ConnectionString);
MySqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM NewsReleases";
MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
List<NewsRelease> NewsReleases = new List<NewsRelease>();
foreach (DataRow row in ds.Tables[0].Rows)
{
var newsRelease = new NewsRelease
{
NewsReleaseId = (int)row["NewsReleaseId"],
Title = (string)row["Title"],
Content = (string)row["Content"],
Images = Convert.ToBoolean((int)row["Images"]),
MediaAdvisory = Convert.ToBoolean((int)row["MediaAdvisory"]),
PublicAdvisory = Convert.ToBoolean((int)row["PublicAdvisory"]),
Time = (DateTime)row["Time"],
DatePublished = (DateTime)row["DatePublished"],
DateCreated = (DateTime)row["DateCreated"],
DateModified = (DateTime)row["DateModified"],
ModifiedBy = (string)row["ModifiedBy"],
HasFrenchVersion = Convert.ToBoolean((int)row["HasFrenchVersion"])
};
NewsReleases.Add(newsRelease);
}
return NewsReleases;
}
It’s just one of the rows that you retrieve from the base has not the type that you expect it has to have.
To identify an issue, and resolve it in consiquence, intialize
newReleasein row-by-row, so the runtime will hit on the exact row where problem happens.One time problem identified and resolved, you can, if you like, come back to intialization way you did before.