开发者

Specified cast is not valid when using casting

I'm getting the following error when trying to get the sum in this Linq query:

InvalidCastException was unhandled. Specified cast is not valid.

I used the DataType property to triple check is that column is in fact a Double, and it is.

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 = _dttMa开发者_运维技巧sterViewTransaction.AsEnumerable().Where(s => (int)r["Entity"] == FundsID).Sum(s => (double)s["CR"])

}).First();

Any suggestions on why this could occur?


Are any of the entries null for that field? or are there some that are not doubles?

we'd need to see more data to get a better answer...


If the values can be either null or an empty string, try this:

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"]))


You may want to use Nullable form of 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"])

Check this link for more details:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜