【问题标题】:Specified cast is not valid when using casting使用强制转换时指定的强制转换无效
【发布时间】:2011-08-03 16:04:25
【问题描述】:

我在尝试获取 此 Linq 查询中的总和时遇到以下错误:

InvalidCastException 未处理。指定的演员表无效。

我使用 DataType 属性三重检查该列是否实际上是 Double,它确实是。

foreach (DataColumn item in _dttMasterViewTransaction.Columns)
{
    if (item.ColumnName == "Dr")
    {
        //Outputs: System.Double!
        MessageBox.Show(item.DataType.ToString());
    }
}

var datos = _dttMasterViewTransaction.AsEnumerable().Where(r => (int)r["Entity"] == FundsID).Select(r => new EntityJESummary()
{
    JEId = (int)r["JE ID"],
    JEGroupingId = (int)r["JE Group"],
    PartnershipId = (int)r["Entity"],
    BookingDate = Convert.ToDateTime(r["GL Date"]),
    EffectiveDate = Convert.ToDateTime(r["Effective Date"]),
    Allocated = Convert.ToBoolean(r["Allocated"]),
    JEEstate = (int)r["JE State"],
    JEComments = r["JE Comments"].ToString(),

    Debit = _dttMasterViewTransaction.AsEnumerable().Where(s => (int)r["Entity"] == FundsID).Sum(s => (double)s["Dr"]),
    Credit = _dttMasterViewTransaction.AsEnumerable().Where(s => (int)r["Entity"] == FundsID).Sum(s => (double)s["CR"])

}).First();

关于为什么会发生这种情况的任何建议?

【问题讨论】:

  • 您是否试图将字符串转换为ints?

标签: c# linq casting double datarow


【解决方案1】:

该字段的任何条目是否为空?还是有一些不是双打的?

我们需要查看更多数据才能获得更好的答案...

【讨论】:

  • 顺便说一句,以防万一有人遇到同样的麻烦。我用过:.Sum(s => (s["Dr"] == DBNull.Value) ? 0 : Convert.ToDouble(s["Dr"]))
  • DBNull 东西至少咬了每个人一次。我不确定他们为什么选择为 null 设置一个特殊的标记值,而不是仅仅使用 null ..
【解决方案2】:

如果值可以是 null 或空字符串,试试这个:

Debit = _dttMasterViewTransaction.AsEnumerable().Where(s => (int)r["Entity"] == FundsID).Sum(s => (String.IsNullOrEmpty(s["Dr"]) ? 0d : (double)s["Dr"])),
Credit = _dttMasterViewTransaction.AsEnumerable().Where(s => (int)r["Entity"] == FundsID).Sum(s => (String.IsNullOrEmpty(s["CR"]) ? 0d : (double)s["CR"]))

【讨论】:

    【解决方案3】:

    您可能希望使用 Nullable 形式的 Sum。

    Debit = _dttMasterViewTransaction.AsEnumerable().Where(s => (int)r["Entity"] == 
    FundsID).Sum(s => (double?)s["Dr"]),     
    Credit = _dttMasterViewTransaction.AsEnumerable().Where(s => (int)r["Entity"] == 
    FundsID).Sum(s => (double?)s["CR"])
    

    查看此链接了解更多详情:

    http://weblogs.asp.net/zeeshanhirani/archive/2008/07/15/applying-aggregates-to-empty-collections-causes-exception-in-linq-to-sql.aspx

    【讨论】:

      猜你喜欢
      • 2011-12-14
      • 1970-01-01
      • 2018-05-27
      • 2014-07-30
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多