我有一个数据库表事务(transactionID,LocalAmount ...)。其中 Localmount 属性的数据类型是float。在用户界面上我试图返回SUM按钮单击事件中一行中的列 (Localamount)。
我用过decimal代替float
但是我在转换到的代码上遇到错误decimal
System.NotSupportedException was unhandled by user code
Message=Casting to Decimal is not supported in LINQ to Entities queries, because the required precision and scale information cannot be inferred.
The
public static IEnumerable<TransactionTotalForProfitcenter> GetTotalTransactionsForProfitcenter(int profitcenterID)
{
List<TransactionTotalForProfitcenter> transactions = new List<TransactionTotalForProfitcenter>();
using (var context = new CostReportEntities())
{
transactions = (from t in context.Transactions
join comp in context.Companies on t.CompanyID equals comp.CompanyID
join c in context.Countries on comp.CountryID equals c.CountryID
where c.CountryID.Equals(comp.CountryID) && t.CompanyID == comp.CompanyID
join acc in context.Accounts
on t.AccountID equals acc.AccountID
join pc in context.Profitcenters
on t.ProfitcenterID equals pc.ProfitcenterID
group t by pc.ProfitcenterCode into tProfitcenter
select new TransactionTotalForProfitcenter
{
ProfitcenterCode = tProfitcenter.Key,
//the error is occurring on the following line
TotalTransactionAmount = (decimal)tProfitcenter.Sum(t => t.LocalAmount),
//the error is occurring on the following line
TotalTransactionAmountInEUR = (decimal)tProfitcenter.Sum(t => t.AmountInEUR) //the error is occurring on this line
}
).ToList();
}
return transactions;
}
我尝试了以下帖子中的一些选项,但没有成功。
- LINQ to SQL 奇怪的浮点行为 https://stackoverflow.com/a/1817557/1108500
- 从十进制转换为浮点型 https://stackoverflow.com/a/1817557/1108500
谁能指出我可以尝试哪些其他选择。如果我对 LINQ 的了解太微不足道,请原谅我。
实体框架表明它不支持您想要的转换。一种解决方法是简单地在数据库中执行尽可能多的工作,然后在内存中完成该过程。在您的情况下,您可以以其本机类型计算总和,将结果作为匿名类型拉入内存,然后在构造实际需要的类型时执行转换。要获取原始查询,您可以进行以下更改:
select new // anonymous type from DB
{
ProfitcenterCode = tProfitcenter.Key,
// notice there are no conversions for these sums
TotalTransactionAmount = tProfitcenter.Sum(t => t.LocalAmount),
TotalTransactionAmountInEUR = tProfitcenter.Sum(t => t.AmountInEUR)
})
.AsEnumerable() // perform rest of work in memory
.Select(item =>
// construct your proper type outside of DB
new TransactionTotalForProfitcenter
{
ProfitcenterCode = item.ProfitcenterCode,
TotalTransactionAmount = (decimal)item.TotalTransactionAmount
TotalTransactionAmountInEUR = (decimal)item.TotalTransactionAmountInEUR
}
).ToList();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)