首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >指定的强制转换在使用强制转换时无效。

指定的强制转换在使用强制转换时无效。
EN

Stack Overflow用户
提问于 2011-08-03 16:04:25
回答 3查看 3.4K关注 0票数 0

当我试图在这个Linq查询中获得和时,我得到了以下错误

InvalidCastException没有被处理。指定的强制转换无效。

我使用DataType属性对列进行三重检查,即列实际上是一个双列,而且它是双列。

代码语言:javascript
复制
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();

对于为什么会发生这种情况,有什么建议吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-08-03 16:08:16

该字段的任何条目为null吗?还是有一些不是双倍的?

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

票数 1
EN

Stack Overflow用户

发布于 2011-08-03 16:24:19

如果值可以为null或空字符串,请尝试如下:

代码语言:javascript
复制
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"]))
票数 0
EN

Stack Overflow用户

发布于 2011-08-03 16:28:06

您可能希望使用可空的求和形式。

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6929539

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档