Reputation: 21638
If I have a poco class
public class Entry
{
public double Quantity { get; set; }
public decimal Cost{ get; set; }
}
How can I do arithmetic on them in a Linq query with something like
context.Entries.Sum(e => (decimal)e.Quantity * e.Cost);
I get Unable to cast object of type 'System.Double' to type 'System.Decimal'
Edit: I have cast the decimal to double and it works.
context.Entries.Sum(e => e.Quantity * (double)e.Cost);
Upvotes: 0
Views: 2297
Reputation: 13488
If you insist on performing all calculations at database side and you have problems with casting, you can use static methods of SqlFunctions
class, but of course, it will have performance overhead:
var result = context.Entries
.Sum(x => SqlFunctions.Exp(SqlFunctions.Log(x.Quantity) + SqlFunctions.Log(x.Cost)));
Explanation: e^(ln(Quantity) + ln(Cost)) = e^(ln(Quantity * Cost)) = Quantity * Cost
Or you can try to write query manually:
var result = context.Database
.SqlQuery<decimal>("select sum(Quantity * Cost) from dbo.Entries)").FirstOrDefault();
Upvotes: 0
Reputation: 611
Entity Framework is indicating it does not support the conversion you desire.To take your original query, you can make the following change:
context.Entries
.AsEnumerable() // perform rest of work in memory
.Sum(e => (decimal)e.Quantity * e.Cost);
Upvotes: 3
Reputation: 10429
You can use Convert.ToDecimal()
context.Entries.Sum(d => Convert.ToDecimal(d.Quantity)*d.Cost)
Edit as stated by Tetsuya Yamamoto if you are not using an enumrable collection
context.Entries.ToList().Sum(d => Convert.ToDecimal(d.Quantity)*d.Cost)
Upvotes: 1