gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:38:53 26 4
gpt4 key购买 nike

我有一个 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 允许您使用 DbFunction 属性将 CLR 函数映射到数据库函数。不幸的是,看起来内置的 castconvert 不是函数,看起来您不能映射到它们。

相反,您可以创建一个 UDF,它执行转换并将其映射到 DbModel 中。映射 API 很复杂,所以我会使用 Code First Functions 库为您完成。 (如果您首先使用数据库或模型,您可以在 SSDL 和 CSDL1 中手动进行映射)。此外,无法在 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 文章。

关于c# - 我可以在 LINQ to Entities 查询中使用 CAST 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34062410/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com