从Entity Framework LINQ查询调用UDF时出错

时间:2010-11-15 19:27:19

标签: linq entity-framework-4 user-defined-functions

我遇到了从LINQ查询调用用户定义函数的问题。我正在使用.NET 4.0框架和VS 2010.以下是edmx函数定义的XML快照。

  <Schema Namespace="MystoreDWModel.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2008" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/02/edm/ssdl">
    <Function Name="RegularPrice" store:Name="RegularPrice" IsComposable="true" Schema ="MystoreDWExtension.mystore" Aggregate="false" BuiltIn="false" ReturnType="decimal" StoreFunctionName="fn_GetPrice">
      <Parameter Name="ProductID" Type="varchar" Scale="40" Mode="In"/>
      <Parameter Name="PriceTypeID" Type="varchar" Scale="10" Mode="In"/>
      <Parameter Name="GroupCode" Type="varchar" Scale="10" Mode="In"/>
      <Parameter Name="GroupValue" Type="varchar" Scale="10" Mode="In"/>
      <Parameter Name="EffectiveDate" Type="datetime" Mode="In"/>
    </Function>

我在代码中定义了以下函数存根...

[EdmFunction("MystoreDWModel.Store", "RegularPrice")]
public decimal? RegularPrice(
    string ProductID,
    string PriceTypeID,
    string GroupCode,
    string GroupValue,
    DateTime EffectiveDate)
{
    throw new NotImplementedException("You can only call this method as part of a LINQ expression");
}

我用来访问该功能的电话如下......

 MystoreDWEntities4 test = new MystoreDWEntities4();

 var prices = (from products in test.Products
               select RegularPrice("PRODUCTID", "R", "D", "20", DateTime.Now));

当我尝试访问价格数据时,收到以下错误...

    The specified method
'System.Nullable`1[System.Decimal] RegularPrice
(System.String, System.String, System.String, System.String, System.DateTime)'
on the type 'EntityFrameworkTest.Form1' cannot be translated
into a LINQ to Entities store expression because the instance
over which it is invoked is not the ObjectContext over which
the query in which it is used is evaluated.

我尝试了几种配置变化,并且无效。有没有人之前遇到过这个错误,我可以使用哪些步骤来修复它?

2 个答案:

答案 0 :(得分:3)

尝试将RegularPrice方法放入MystoreDWEntities4类定义中(使用部分声明,如下例所示):

public partial class MystoreDWEntities4 {
  [EdmFunction("MystoreDWModel.Store", "RegularPrice")]
  public decimal? RegularPrice(
    string ProductID,
    string PriceTypeID,
    string GroupCode,
    string GroupValue,
    DateTime EffectiveDate)
  {
    throw new NotImplementedException("You can only call this method as part of a LINQ expression");
  }
}  

然后将其称为ObjectContext实例方法,如下所示:

ObjectSet<Products> products = test.Products;  
var prices = from prod in products  
             select new { Price = test.RegularPrice("PRODUCTID", "R", "D", "20", DateTime.Now)};

答案 1 :(得分:0)

将方法定义为扩展方法,而不是普通的普通方法。

http://jendaperl.blogspot.com/2010/11/specified-method-xxx-on-type-yyy-cannot.html