【问题标题】:System.InvalidCastException: Specified cast is not valid. ErrorSystem.InvalidCastException:指定的强制转换无效。错误
【发布时间】:2013-08-27 14:54:06
【问题描述】:

我在一个 C# ASP.NET 项目上。

我有一个 MySQL 表,其用户 ID 字段类型为 int

现在我想使用 LINQ 获取 userid 的值等于某个值的行数。

为此,我编写了以下方法:

public int getCount(int usercode) {
    int count = 0;
    DataTable mytable = getAllRowsAndReturnAsDataTable(); // assigning a DataTable value to mytable. 
    if (mytable.Rows.Count > 0) { 
        count = (from x in mytable.AsEnumerable() where x.Field<Int32>("userid") == usercode select x).Count();
    } 
    return count;
}

但它显示错误System.InvalidCastException: Specified cast is not valid.,在红色突出显示区域显示count = (from x in mytable.AsEnumerable() where x.Field&lt;Int32&gt;("userid") == usercode select x).Count();

我不知道我在这里做错了什么。请帮忙。

【问题讨论】:

    标签: c# asp.net mysql linq


    【解决方案1】:

    InvalidCastException 最可能的原因是x.Field&lt;Int32&gt;("userid") 行。如果数据的实际类型与传递给Field&lt;T&gt; 的类型不匹配,Field&lt;T&gt; 扩展方法将抛出InvalidCastException。因此,如果 userid 不是 Int32 这会抛出。

    编辑

    根据您的 cmets,userid 的类型实际上是 UInt32 而不是 Int32。这就是导致问题的原因。尝试使用以下内容,它应该可以工作

    x.Field<UInt32>("userid")
    

    【讨论】:

    • mysql&gt; desc vticketuser; +--------------+------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------+------------------+------+-----+---------+-------+ | idticket | int(10) unsigned | NO | | 0 | | | userid | int(10) unsigned | NO | | NULL | | 这是字段
    • @user2168042 您将数据库定义与托管代码时的值混合在一起。尝试查看代码中的原始 "userid" 值,在其上调用 .GetType 并查看它被创建为什么类型
    • 我不知道我做得对吗.. 但我尝试过这样string ty = t.Rows[0]["userid"].GetType().ToString(); 它说“System.UInt32”
    • #@user2168042 那就是问题所在。类型是UInt32,它不同于Int32。在Field&lt;T&gt; 调用中改用UInt32,它应该可以正常工作
    【解决方案2】:

    如果不查看从您的数据库返回的数据,我只能猜测您的 LINQ 的以下部分有问题:

    x.Field<Int32>("userid")
    

    您的 userid 列值可能不是 int,我会把钱放在它为 NULL 上吗?

    更新:您能确认不是 Field 调用中断了吗?只需在没有 Field 调用的情况下将您的代码更改为类似这样:

    public int getCount(int usercode){
      int count = 0;
      DataTable mytable = getAllRowsAndReturnAsDataTable(); // assigning a DataTable value to mytable. 
      if (mytable.Rows.Count > 0) { 
        count = mytable.AsEnumerable().Count();  // No WHERE function call so no casting.
      } 
      return count;
    }
    

    例如,您还可以在监视窗口中检查 mytable.AsEnumerable() 返回的值是什么,以确保一切看起来正确。如果上面的代码有效,那么它就是 Field 调用爆炸了。找出哪一行不能转换为 Int32 并从那里开始。

    如果它实际上是 NULL,有很多方法可以解决这个问题。

    1. 确保您不会从数据库查询中返回 NULL,在 MySQL 中您可以使用 IFNULL
    2. 对传递给 Field 的泛型使用可为空的类型:

      其中 x.Field("userid") == (Int32?)usercode

    【讨论】:

    • 它的 Int 我 100% 确定。我重新检查了它。
    • @user2168042 - 更新了答案,提供了更多关于如何确定数据是否正确以及 Field 是否确实是问题的详细信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    相关资源
    最近更新 更多