jus*_*mer 7 c# linq sql-server entity-framework entity-sql
我有一个LINQ to Entities查询
From item In ctx.Items
Select new {
    ListPrice = item.Cost / (1M - item.Markup)
};
我可以指定EF,我希望它应用cast查询和物化之前将其标价1?有什么EntityFunctions.Cast可能吗?或者我可以使用ESQL cast功能吗?
我希望LINQ能够沿着这些方向生成SQL查询
SELECT cast((Cost / (1 - Markup)) as decimal(10, 2)) AS ListPrice
1我的目标是摆脱一堆精度/缩放查询.因为有十进制减法和除法,所以数学结果是小数(38,26)!这比.NET可以处理的更多,而且超出了我的需要.
EF 允许您使用属性将 CLR 函数映射到数据库函数DbFunction。不幸的是,它看起来像内置cast的convert不是函数,并且看起来您无法映射到它们。
相反,您可以创建一个 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))
};
| 归档时间: | 
 | 
| 查看次数: | 1700 次 | 
| 最近记录: |