我有一个数据库表Transaction(transactionID,LocalAmount ...)。其中Localamount属性的数据类型为 float 。在UI上我试图在按钮单击事件的一行中返回 SUM 列(Localamount)。
我使用十进制而不是 float
但是我在转换为十进制
的代码时收到错误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的一点知识,如果它太琐碎了。
答案 0 :(得分:12)
实体框架表明它不支持您想要的转换。一种解决方法是尽可能简单地在数据库中执行尽可能多的工作,然后在内存中完成该过程。在您的情况下,您可以计算其本机类型的总和,将结果作为匿名类型提取到内存中,然后在构建实际需要的类型时执行转换。要获取原始查询,您可以进行以下更改:
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();
答案 1 :(得分:1)
我建议您在查询完成后进行演员
var somevar = (decimal)transactions.YourValue
答案 2 :(得分:1)
有时需要施放,如果超过两个十进制宫殿
double TotalQty;
double.TryParse(sequence.Sum(x => x.Field<decimal>("itemQty")).ToString(),out TotalQty);
答案 3 :(得分:0)
如果您不太喜欢调用AsEnumerable,则可以通过一些数学将其转换为int
而不是十进制。
(((decimal)((int)(x.Discount * 10000))) / 10000)
每个零实际上代表转换将具有的精度。
从this得到了这个答案。只需看一下文件末尾即可。