简体   繁体   中英

SQL query get error “Specified cast is not valid.”

I have sample codes as below:-

public List<Announcement_User> announcementUser([FromBody]MyAnnouncementUser value)
{
    MySqlConnection conn = WebApiConfig.conn();
    MySqlCommand query = conn.CreateCommand();
    query.CommandText = "select a.title,a.description,a.date_created,ua.read,ua.announcement_id,ua.user_announcement_id from announcement a left join user_announcement ua on a.announcement_id = ua.announcement_id where ua.user_id = @user_id";

    query.Parameters.AddWithValue("@user_id", value.user_id);

    var prodWishlist = new List<Announcement_User>();

    try
    {
        conn.Open();
    }
    catch (MySql.Data.MySqlClient.MySqlException ex)
    {
        prodWishlist.Add(new Announcement_User(null, null,null, false, 0, 0, ex.ToString()));
    }

    MySqlDataReader fetch_query = query.ExecuteReader();

    while (fetch_query.Read())
    {
        prodWishlist.Add(new Announcement_User(fetch_query["title"].ToString(), fetch_query["description"].ToString(), fetch_query["date_created"].ToString(), (bool)fetch_query["read"], fetch_query.GetInt32(4), fetch_query.GetInt32(5), null));
    }
    conn.Close();
    return prodWishlist;
}

And I hit error as below:-

"Message": "An error has occurred.",

"ExceptionMessage": "Specified cast is not valid.",

"ExceptionType": "System.InvalidCastException",

Now I suspect the error caused by bool. May I know how can I write correct way for bool in(fetch_query.Read())? Please help. Thank you.

尝试使用GetBoolean方法:

fetch_query.GetBoolean("read")

I would recommend to you to retrieve all of the values beforehand using column name instead of column index and create new object when required parameters have values:

string title = fetch_query["title"].ToString();
string description = fetch_query["description"].ToString();
// ...
object read = fetch_query["read"];
object integer1 = fetch_query[4];
// ...

// newest C# approach
if ( read != null && bool.TryParse(read.ToString(), out bool b_read) )

// old c# approach
bool b_read = false;
if ( read != null && bool.TryParse(read.ToString(), out b_read) )

Check for every required property

prodWishlist.Add(
    new Announcement_User(
        title,
        description, 
// ..
        b_read,
        i_integer1
//...
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM