当我试图在这个Linq查询中获得和时,我得到了以下错误
InvalidCastException没有被处理。指定的强制转换无效。
我使用DataType属性对列进行三重检查,即列实际上是一个双列,而且它是双列。
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();对于为什么会发生这种情况,有什么建议吗?
发布于 2011-08-03 16:08:16
该字段的任何条目为null吗?还是有一些不是双倍的?
我们需要看到更多的数据才能得到更好的答案..。
发布于 2011-08-03 16:24:19
如果值可以为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"]))发布于 2011-08-03 16:28:06
您可能希望使用可空的求和形式。
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
https://stackoverflow.com/questions/6929539
复制相似问题