I have a LINQ to Entities query
From item In ctx.Items
Select new {
ListPrice = item.Cost / (1M - item.Markup)
};
Can I specify to EF that I want it to apply a cast to the list price before querying and materializing it1? Is there something like EntityFunctions.Cast maybe? Or can I use the ESQL cast function?
I want the LINQ to generate a SQL query along these lines
SELECT cast((Cost / (1 - Markup)) as decimal(10, 2)) AS ListPrice
1My goal is to get rid of a bunch of precision/scale the query. Because there's decimal subtraction and division, the result of the math is a decimal(38, 26)! That's way more than .NET can handle and more than I need.
EF allows you to map CLR functions to database functions using the
DbFunctionattribute. Unfortunately, it looks like the built incastandconvertare not functions and it does not look like you can map to them.Instead you can create a UDF which does the cast and map it in the
DbModel. The mapping API is complicated so I would use the Code First Functions library to do it for you. (If your using Database first or Model first, you can do the mapping manually in your SSDL and CSDL1). Also, there's no way to do dynamic casting inside a UDF so you'll need to pick write separate functions for each cast you want. Here's an example for acast(field as decimal(10,4).1 See this blog post or this MSDN article for more details.