Only Bolivian Here
Only Bolivian Here

Reputation: 36733

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 = _dttMasterViewTransaction.AsEnumerable().Where(s => (int)r["Entity"] == FundsID).Sum(s => (double)s["CR"])

}).First();

Any suggestions on why this could occur?

Upvotes: 0

Views: 3400

Answers (3)

Asdfg
Asdfg

Reputation: 12203

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

Upvotes: 0

Matten
Matten

Reputation: 17631

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

Upvotes: 0

John Gardner
John Gardner

Reputation: 25116

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...

Upvotes: 1

Related Questions