【IT168技术文档】
用户定义函数
我们可以在LINQ to SQL中使用用户定义函数。我们只要把用户定义函数拖到O/R设计器中,LINQ to SQL自动使用FunctionAttribute属性和 ParameterAttribute属性(如果需要)将其函数指定为方法。这时,我们只需简单调用即可。
在这里注意:使用用户定义函数的时候必须满足以下形式之一,否则会出现InvalidOperationException异常情况。
* 具有正确映射属性的方法调用的函数。这里使用FunctionAttribute属性和 ParameterAttribute属性。
* 特定于LINQ to SQL的静态SQL方法。
* .NET Framework方法支持的函数。
下面介绍几个例子:
1.在Select中使用用户定义的标量函数
所谓标量函数是指返回在 RETURNS 子句中定义的类型的单个数据值。可以使用所有标量数据类型,包括 bigint 和 sql_variant。不支持 timestamp 数据类型、用户定义数据类型和非标量类型(如 table 或 cursor)。在 BEGIN...END 块中定义的函数主体包含返回该值的 Transact-SQL 语句系列。返回类型可以是除 text、ntext、image、cursor 和 timestamp 之外的任何数据类型。我们在系统自带的NORTHWND.MDF数据库中,有3个自定义函数,这里使用TotalProductUnitPriceByCategory,其代码如下:
我们将其拖到设计器中,LINQ to SQL通过使用 FunctionAttribute 属性将类中定义的客户端方法映射到用户定义的函数。请注意,这个方法体会构造一个捕获方法调用意向的表达式,并将该表达式传递给 DataContext 进行转换和执行。ALTER FUNCTION [dbo].[TotalProductUnitPriceByCategory] (@categoryID int) RETURNS Money AS BEGIN -- Declare the return variable here DECLARE @ResultVar Money -- Add the T-SQL statements to compute the return value here SELECT @ResultVar = (Select SUM(UnitPrice) from Products where CategoryID = @categoryID) -- Return the result of the function RETURN @ResultVar END
[Function(Name="dbo.TotalProductUnitPriceByCategory", IsComposable=true)] public System.Nullable<decimal> TotalProductUnitPriceByCategory( [Parameter(DbType="Int")] System.Nullable<int> categoryID) { return ((System.Nullable<decimal>)(this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), categoryID).ReturnValue)); }
2.在Where从句中使用用户定义的标量函数我们使用时,可以用以下代码来调用: var q = from c in db.Categories select new { c.CategoryID, TotalUnitPrice = db.TotalProductUnitPriceByCategory(c.CategoryID) }; 这时,LINQ to SQL自动生成SQL语句如下: SELECT [t0].[CategoryID], CONVERT(Decimal(29,4), [dbo].[TotalProductUnitPriceByCategory]([t0].[CategoryID])) AS [TotalUnitPrice] FROM [dbo].[Categories] AS [t0]
这个例子使用方法同上一个例子原理基本相同了,MinUnitPriceByCategory自定义函数如下:
ALTER FUNCTION [dbo].[MinUnitPriceByCategory] (@categoryID INT ) RETURNS Money AS BEGIN -- Declare the return variable here DECLARE @ResultVar Money -- Add the T-SQL statements to compute the return value here SELECT @ResultVar = MIN(p.UnitPrice) FROM Products as p WHERE p.CategoryID = @categoryID -- Return the result of the function RETURN @ResultVar END