使用Entity Framework 6调用DB函数

我按照这些说明将标量函数添加到我的Entity Framework 6数据模型中。 如何使用带有linq的标量值函数实体?

但是,我无法在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查询中调用数据库函数?

此外,如果查询代码有时会针对数据库执行,有时会在内存中执行,有没有办法以两种情况下的方式调用函数? 我有一个相同function的C#版本。

谢谢

编辑:这是我正在尝试使用的function。

 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) HeightCalc = HeightCalc + (DepthCalc - HeightCalc) * ratio; return (float)Math.Round(HeightCalc * DepthCalc * .12, 1); } else return null; } 

它也可以像这样写成一行。 这条线可以在我需要使用它的任何地方进行复制/粘贴,但这会产生非常难看的代码,尽管这可能有效。 我宁愿把它作为一个function。

 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); 

我找到了答案。 虽然我发现很少有关于EdmFunctionAttribute已经过时的Entity Framework 6的文档,但我得到了这个代码。

在EDMX文件中,IsComposable必须为True,并且必须删除CommandText。 我只需要没有函数import的函数声明。

然后,在我的数据上下文的部分类中,我创建了这个函数

 [DbFunction("NaturalGroundingVideosModel.Store", "fn_GetRatingValue")] public float? DbGetValue(float? height, float? depth, float ratio) { List parameters = new List(3); parameters.Add(new ObjectParameter("height", height)); parameters.Add(new ObjectParameter("depth", depth)); parameters.Add(new ObjectParameter("ratio", ratio)); var lObjectContext = ((IObjectContextAdapter)this).ObjectContext; var output = lObjectContext. CreateQuery("NaturalGroundingVideosModel.Store.fn_GetRatingValue(@height, @depth, @ratio)", parameters.ToArray()) .Execute(MergeOption.NoTracking) .FirstOrDefault(); return output; } 

我将该函数添加到MediaRating对象,因此我可以调用它而无需引用数据上下文。

 var Test2 = (from r in context.MediaRatings select r.DbGetValue(r.Height, r.Depth, 0)).ToList(); 

这有效!