2010-11-15 84 views
0

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

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

我已经尝试了几种变体的配置,并且无济于事。以前有没有人跑过这个错误,我可以用什么步骤来修复它?

+0

您是否尝试过实体SQL,像朱莉·勒曼建议在这个职位:http://thedatafarm.com/blog/data-access/calling-udfs-from-entity-framework-not-what-你可能有预期/? – Devart 2010-11-16 15:29:47

+0

@Devart是的....上面是那个结果....它没有出现在门外,所以我一直在搞这个,不幸的是它不能让它合作。 – 2010-11-18 17:00:27

回答

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