如何在Entity Framework 4中的LINQ表达式中执行Oracle函数?

我使用的是Visual Studio 2010,C#,Entity Framework 4和Oracle 10g。

我需要能够将数据库函数的结果作为匿名类型的标量属性返回。

我的Oracle模式有两个表,PARENT和CHILD,以及一个函数FNC_ADD。 我使用Visual Studio ADO.NET实体数据模型模板创建了一个实体模型,包括表和函数。

我的.edmx文件的StorageModels部分如下所示:

                                                 

我创建了一个扩展方法来定义实体数据模型的函数,如下所示:

 public partial class LINQtest2Entities { [EdmFunction("LINQtest2Model", "FNC_ADD")] public decimal FNC_ADD(decimal V1, decimal V2) { // don't need to implement the function throw new ApplicationException(); } } 

我在LINQ表达式中调用函数,如下所示:

 using (var context = new LINQtest2Entities()) { var parents = from p in context.PARENTs select new { children = from c in p.Children select new { p.PARENT_ID, c.CHILD_ID, a = context.FNC_ADD(p.PARENT_ID, c.CHILD_ID) } }; foreach (var parent in parents) { foreach (var child in parent.children) { Console.WriteLine("P {0} C {1} A {2}", child.PARENT_ID, child.CHILD_ID, child.a); } } } 

一切都正确编译,但是当我运行代码时,我得到了这个:

The specified method 'System.Decimal FNC_ADD(System.Decimal, System.Decimal)' on the type 'LINQtest2.LINQtest2Entities' cannot be translated into a LINQ to Entities store expression.

我究竟做错了什么?

你的命名空间arg到EdmFunctionAttribute看起来很可疑。 这看起来像CLR类型,而不是商店空间。 这篇博客文章可能会帮助您解决这个问题。

使用Model.Store命名空间:

 public partial class LINQtest2Entities { [EdmFunction("LINQtest2Model.Store", "FNC_ADD")] public decimal FNC_ADD(decimal V1, decimal V2) { // don't need to implement the function throw new ApplicationException(); } } 

如果您正确提供了命名空间,一切都很顺利。