Share via


如何:调用用户定义的函数(实体框架)

使用 Entity SQL,您可以在查询中调用用户定义的函数。 可以将这些函数定义为与查询内联,或将它们定义为概念模型的一部分。 有关更多信息,请参见用户定义函数 (Entity SQL)

本主题中的示例基于 Adventure Works 销售模型。若要运行本主题中的代码,则必须已经将 Adventure Works 销售模型添加到了您的项目中,并且已经将项目配置为使用实体框架。有关更多信息,请参见如何:使用实体数据模型向导(实体框架)如何:手动配置实体框架项目如何:手动定义实体数据模型(实体框架)

示例

下面的示例在 Entity SQL 查询中定义一个名为 OrderTotal 的函数。 此函数采用一个 SalesOrderHeader 对象,并通过将 SubTotalTaxAmtFreight 属性的值相加重新计算总应付金额。 此函数随后在查询投影中被调用,返回重新计算的 TotalDueTotalDue 值返回自数据源。 指定传递给此函数的 SalesOrderHeader 对象的命名空间时,需要使用 USING 运算符。

' Query that calls the OrderTotal function to recalculate the order total. 
Dim queryString As String = "USING Microsoft.Samples.Entity;" & _
    " FUNCTION OrderTotal(o SalesOrderHeader) AS (o.SubTotal + o.TaxAmt + o.Freight)" & _
    " SELECT order.TotalDue AS currentTotal, OrderTotal(order) AS calculated" & _
    " FROM AdventureWorksEntities.SalesOrderHeaders AS order WHERE order.Contact.ContactID = @customer"

Dim customerId As Integer = 364


Using context As New AdventureWorksEntities()
    Dim query As New ObjectQuery(Of DbDataRecord)(queryString, context)
    query.Parameters.Add(New ObjectParameter("customer", customerId))

    For Each rec As DbDataRecord In query
        Console.WriteLine("Order Total: Current - {0}, Calculated - {1}.", rec(0), rec(1))
    Next
End Using
// Query that calls the OrderTotal function to recalculate the order total.
string queryString = @"USING Microsoft.Samples.Entity;
    FUNCTION OrderTotal(o SalesOrderHeader) AS
    (o.SubTotal + o.TaxAmt + o.Freight)

    SELECT [order].TotalDue AS currentTotal, OrderTotal([order]) AS calculated
    FROM AdventureWorksEntities.SalesOrderHeaders AS [order]
    WHERE [order].Contact.ContactID = @customer";

int customerId = 364;


using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    ObjectQuery<DbDataRecord> query = new ObjectQuery<DbDataRecord>(queryString, context);
    query.Parameters.Add(new ObjectParameter("customer",customerId));

    foreach (DbDataRecord rec in query)
    {
        Console.WriteLine("Order Total: Current - {0}, Calculated - {1}.", 
            rec[0], rec[1]);
    }
}

另请参见

任务

如何:在查询中调用模型定义函数 (LINQ to Entities)

概念

用户定义函数 (Entity SQL)

其他资源

How to: Define Custom Functions in the Conceptual Model
How to: Define Custom Functions in the Conceptual Model