我可以在LINQ to Entities查询中使用CAST吗?

时间:2015-12-03 09:37:28

标签: c# sql-server entity-framework linq entity-sql

我有一个LINQ to Entities查询

From item In ctx.Items
Select new {
    ListPrice = item.Cost / (1M - item.Markup)
};

我可以指定EF,我希望它在查询并实现 1 之前将cast应用于定价吗?是否有类似EntityFunctions.Cast的东西?或者我可以使用ESQL cast函数吗?

我希望LINQ能够沿着这些行生成SQL查询

SELECT cast((Cost / (1 - Markup)) as decimal(10, 2)) AS ListPrice

1 我的目标是摆脱一堆精度/缩放查询。因为有十进制减法和除法,所以数学结果是小数(38,26)!这比.NET可以处理的更多,而且超出了我的需要。

1 个答案:

答案 0 :(得分:2)

EF允许您使用DbFunction属性将CLR函数映射到数据库函数。不幸的是,看起来内置的castconvert不是函数,它们看起来不像你可以映射到它们。

相反,您可以创建一个UDF来执行强制转换并将其映射到DbModel。映射API很复杂,所以我会使用Code First Functions库为您完成。 (如果您首先使用数据库或首先使用模型,则可以在SSDL和CSDL 1 中手动执行映射)。此外,无法在UDF中进行动态转换,因此您需要为每个所需的转换选择单独的函数。以下是cast(field as decimal(10,4)的示例。

-- In SQL Server
CREATE FUNCTION ClrRound_10_4
(
    @value decimal(28, 10)
)
RETURNS decimal(10,4)
AS
BEGIN
    DECLARE @converted decimal(10,4)

    SELECT @converted = cast(round(@value, 4) as decimal(10,4))

    RETURN @converted

END
GO
//In your DbContext class
using CodeFirstStoreFunctions;

public class MyContext : DbContext {
    protected override void OnModelCreating(DbModelBuilder builder) {
        builder.Conventions.Add(new FunctionsConvention("dbo", typeof(Udf));
    }

    //etc
}

//In a static class named Udf (in the same namespace as your context)
using System.Data.Entity;

public static class Udf {
    [DbFunction("CodeFirstDatabaseSchema", "ClrRound_10_4")]
    public static decimal ClrRound_10_4(decimal value) {
        throw new InvalidOperationException("Cannot call UDF directly!");
    }
}

//In your LINQ query
from item in ctx.Items
select new {
    ListPrice = Udf.ClrRound_10_4(item.Cost / (1M - item.Markup))
};

1 有关详细信息,请参阅此blog post或此MSDN文章。

相关问题