【发布时间】:2014-11-19 03:18:40
【问题描述】:
我按照这些说明将标量函数添加到我的 Entity Framework 6 数据模型中。 How to use scalar-valued function with linq to entity?
但是,我无法在 LINQ 查询中调用该函数,尽管直接在 DataContext 上调用该方法是可行的。
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);
【问题讨论】:
-
没有 cmets。有人对这个有任何想法吗?
-
我设法通过在 EDMX 文件中将所有函数参数名称作为小写字母来消除 6046 警告,但我仍然无法在查询中使用该函数。
-
以这种方式做事让人头疼,这可能是人们不想解决这个问题的原因。我要做的是在 SQL 中做所有事情:从中创建一个视图。然后,您可以将视图添加为模型类(或者在您使用 Visual Studio 中的 Code First 生成实体框架连接“ADO .NET 实体”时让它为您完成)。然后您可以使用该模型来检索结果。然后,您可以对返回的数据集执行 LINQ 查询,或者使用
foreach循环提取数据并使用if语句将高度/深度值与您的比率进行比较来设置您的标准。
标签: c# sql linq entity-framework-6