2010-11-15 83 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)};