Casting to Decimal is not supported in LINQ to Entities queries

前端 未结 4 1574
后悔当初
后悔当初 2021-02-14 01:58

I have a database table Transaction (transactionID, LocalAmount...). where datatype for Localamount property is float. ON the UI I am trying to return a

相关标签:
4条回答
  • 2021-02-14 02:38

    If you don't happen to have the luxury of calling AsEnumerable than you can convert it to int and than to decimal with some math.

     (((decimal)((int)(x.Discount * 10000))) / 10000)
    

    Each zero actually represents the precision that the conversion is going to have.

    Got this answer from this. Just take a look at the end of the file.

    0 讨论(0)
  • 2021-02-14 02:41

    I would suggest you make the cast after your query has finished

    var somevar = (decimal)transactions.YourValue
    
    0 讨论(0)
  • 2021-02-14 02:58

    Entity Framework is indicating it does not support the conversion you desire. One workaround is to simply execute as much of the work in the database as you can, and then complete the process in memory. In your case, you can calculate the sum in its native type, pull the result into memory as an anonymous type, then perform your conversion as you construct the type you actually need. To take your original query, you can make the following change:

    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();
    
    0 讨论(0)
  • 2021-02-14 03:00

    Sometimes need casting, if more than two decimal palaces

         double TotalQty;
         double.TryParse(sequence.Sum(x => x.Field<decimal>("itemQty")).ToString(),out TotalQty);
    
    0 讨论(0)
提交回复
热议问题