gpt4 book ai didi

c# - LINQ to Entities 查询不支持转换为十进制

转载 作者:可可西里 更新时间:2023-11-01 08:42:02 26 4
gpt4 key购买 nike

我有一个数据库表 Transaction (transactionID, LocalAmount...)。其中 Localamount 属性的数据类型是 float。在 UI 上,我试图在按钮单击事件的一行中返回列 (Localamount) 的 SUM

我使用了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.

 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 的了解。

最佳答案

Entity Framework 表明它不支持您想要的转换。一种解决方法是尽可能多地执行数据库中的工作,然后在内存中完成该过程。在您的情况下,您可以计算其 native 类型的总和,将结果作为匿名类型拉入内存,然后在构建实际需要的类型时执行转换。要进行原始查询,您可以进行以下更改:

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();

关于c# - LINQ to Entities 查询不支持转换为十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14939961/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com