我按照这些说明将一个标量函数添加到我的Entity Framework 6数据模型中。
如何在linq to entity中使用标量值函数?
然而,我无法在LINQ查询中调用该函数,尽管在DataContext上直接调用该方法是有效的。
第二个查询语句出现了错误。
此外,设计师向我发出了警告。
我做错了什么?如何在LINQ查询中调用数据库函数?
此外,如果查询代码有时针对数据库执行,有时在内存中执行,是否有一种方法可以调用该函数以适用于两种情况?我有一个相同功能的C#版本。
谢谢!
编辑:这是我试图使用的函数。
using (Entities context = new Entities()) {
// This works.
var Test1 = context.fn_GetRatingValue(8, 9, 0).FirstOrDefault();
// This doesn't work.
var Test2 = (from r in context.MediaRatings
select context.fn_GetRatingValue(r.Height, r.Depth, 0)).ToList();
}
第二个查询语句出现了错误。
LINQ to Entities does not recognize the method 'System.Data.Entity.Core.Objects.ObjectResult`1[System.Nullable`1[System.Single]] fn_GetRatingValue(System.Nullable`1[System.Single], System.Nullable`1[System.Single], System.Nullable`1[System.Single])' method, and this method cannot be translated into a store expression.
此外,设计师向我发出了警告。
Error 6046: Unable to generate function import return type of the store function 'fn_GetRatingValue'. The store function will be ignored and the function import will not be generated.
我做错了什么?如何在LINQ查询中调用数据库函数?
此外,如果查询代码有时针对数据库执行,有时在内存中执行,是否有一种方法可以调用该函数以适用于两种情况?我有一个相同功能的C#版本。
谢谢!
编辑:这是我试图使用的函数。
public float? GetValue(float? Height, float? Depth, float ratio) {
if (Height != null || Depth != null) {
float HeightCalc = Height ?? Depth.Value;
float DepthCalc = Depth ?? Height.Value;
if (ratio < 0)
DepthCalc = DepthCalc + (HeightCalc - DepthCalc) * -ratio;
else if (ratio > 0)
HeightCalc = HeightCalc + (DepthCalc - HeightCalc) * ratio;
return (float)Math.Round(HeightCalc * DepthCalc * .12, 1);
} else
return null;
}
这段代码也可以写成一行。我可以在需要使用的任何地方复制/粘贴这行代码,但那会产生非常丑陋的代码,虽然这样也可以运行。我更愿意将其保留为一个函数。
return (float)Math.Round(
(Height.HasValue ? Height.Value + (ratio > 0 ? ((Depth ?? Height.Value) - Height.Value) * ratio : 0) : Depth.Value) *
(Depth.HasValue ? Depth.Value + (ratio < 0 ? ((Height ?? Depth.Value) - Depth.Value) * -ratio : 0) : Height.Value)
* .12, 1);
foreach
循环提取数据,并使用if
语句设置您的标准,比较高度/深度值与您的比率。 - vapcguy