[英]Casting to Decimal is not supported in LINQ to Entities queries
我有一個數據庫表Transaction(transactionID,LocalAmount ...)。 其中Localamount屬性的數據類型為float 。 在UI上我試圖在按鈕單擊事件的一行中返回一列SUM (Localamount)。
我用過decimal而不是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的一點知識,如果它太瑣碎了。
實體框架表明它不支持您想要的轉換。 一種解決方法是盡可能簡單地在數據庫中執行盡可能多的工作,然后在內存中完成該過程。 在您的情況下,您可以計算其本機類型的總和,將結果作為匿名類型提取到內存中,然后在構建實際需要的類型時執行轉換。 要獲取原始查詢,您可以進行以下更改:
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();
我建議你在查詢結束后進行演員表
var somevar = (decimal)transactions.YourValue
有時需要施放,如果超過兩個十進制宮殿
double TotalQty;
double.TryParse(sequence.Sum(x => x.Field<decimal>("itemQty")).ToString(),out TotalQty);
如果你碰巧沒有調用AsEnumerable的豪華,那么你可以將它轉換為int
而不是帶有一些數學的十進制。
(((decimal)((int)(x.Discount * 10000))) / 10000)
每個零實際上代表轉換將具有的精度。
得到了這樣的回答這個 。 只需看一下文件的結尾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.