Ошибка вызова UDF из запроса LINQ Entity Framework - PullRequest
0 голосов
/ 15 ноября 2010

Я сталкиваюсь с проблемой вызова пользовательской функции из запроса LINQ.Я использую .NET 4.0 framework и VS 2010. Вот снимок XML для определения функции edmx.

  <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 ]

3 голосов
/ 19 ноября 2010

Попробуйте поместить метод 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)};
0 голосов
/ 24 ноября 2010

Определите метод как метод расширения, а не обычный старый.

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

...