Adrian Brand
Adrian Brand

Reputation: 21638

Multiply decimal and a double in Linq

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

Answers (3)

Slava Utesinov
Slava Utesinov

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

Masoud
Masoud

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

jitender
jitender

Reputation: 10429

You can use Convert.ToDecimal()

context.Entries.Sum(d => Convert.ToDecimal(d.Quantity)*d.Cost)

Here is working fiddle

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

Related Questions