User-Defined Functions
We can use user-defined functions in LINQ to SQL. If you drag a user-defined function to the O/R designer, LINQ to SQL automatically uses the FunctionAttribute and ParameterAttribute (if needed) to specify the function as a method. In this case, we only need to make a simple call.
Note: When using a user-defined function, either of the following forms must be met; otherwise, an InvalidOperationException occurs.
- A function that has the correct ing attribute. The FunctionAttribute and ParameterAttribute are used here.
- Static SQL methods specific to LINQ to SQL.
- Functions supported by the. NET Framework method.
The following are examples:
1. Use User-Defined scalar functions in Select
A scalar function is a single data value of the type defined in the RETURNS clause. All scalar data types can be used, including bigint and SQL _variant. The timestamp data type, user-defined data type, and non-standard data type (such as table or cursor) are not supported ). The function body defined in the BEGIN... END block contains the series of Transact-SQL statements that return this value. The return type can be any data type except text, ntext, image, cursor, and timestamp. We have three user-defined functions in the system's NORTHWND. MDF database. Here we use TotalProductUnitPriceByCategory. The Code is as follows:
ALTER FUNCTION [dbo].[TotalProductUnitPriceByCategory](@categoryID int)RETURNS MoneyASBEGIN -- 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 @ResultVarEND
We drag it into the designer. By using the FunctionAttribute, LINQ to SQL maps the client methods defined in the class to user-defined functions. Note that this method constructs an expression that captures the call intention of a method and passes the expression to DataContext for conversion and execution.
[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));}
You can use the following code to call this function:
var q = from c in db.Categories select new { c.CategoryID, TotalUnitPrice = db.TotalProductUnitPriceByCategory(c.CategoryID) };
In this case, the following SQL statement is automatically generated by the LINQ to SQL statement:
SELECT [t0].[CategoryID], CONVERT(Decimal(29,4),[dbo].[TotalProductUnitPriceByCategory]([t0].[CategoryID]))AS [TotalUnitPrice] FROM [dbo].[Categories] AS [t0]
2. Use User-Defined scalar functions in the Where clause
The usage in this example is basically the same as in the same example. The MinUnitPriceByCategory custom function is as follows:
ALTER FUNCTION [dbo].[MinUnitPriceByCategory](@categoryID INT)RETURNS MoneyASBEGIN -- 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 @ResultVarEND
Drag to the designer to generate the following code:
[Function(Name="dbo.MinUnitPriceByCategory", IsComposable=true)]public System.Nullable<decimal> MinUnitPriceByCategory([Parameter(DbType="Int")] System.Nullable<int> categoryID){ return ((System.Nullable<decimal>)(this.ExecuteMethodCall( this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), categoryID).ReturnValue));}
Now you can use it: note that in the LINQ to SQL query, you can call the generated User-Defined Function Method MinUnitPriceByCategory inline. This function will not be executed immediately because the query will be delayed. The functions contained in the delayed query are not executed until the query is executed. The SQL statement generated for this query is converted into a user-defined function call in the database (see the generated SQL statement after this query). When you call this function externally, using a method call expression to create a simple query and execute it.
var q = from p in db.Products where p.UnitPrice == db.MinUnitPriceByCategory(p.CategoryID) select p;
The automatically generated SQL statement is as follows:
SELECT [t0].[ProductID], [t0].[ProductName], [t0].[SupplierID],[t0].[CategoryID],[t0].[QuantityPerUnit], [t0].[UnitPrice],[t0].[UnitsInStock], [t0].[UnitsOnOrder],[t0].[ReorderLevel],[t0].[Discontinued]FROM [dbo].[Products] AS [t0]WHERE [t0].[UnitPrice] = [dbo].[MinUnitPriceByCategory]([t0].[CategoryID])
3. Use User-Defined Table value functions
The table value function returns a single row set (different from the stored procedure, the stored procedure can return multiple result shapes ). Because the return type of the Table value function is Table, you can use the Table value function anywhere in SQL. In addition, you can process table value functions exactly as you do when processing tables.
The following SQL user-defined letter explicitly declares that it returns a TABLE. Therefore, the returned row set structure is implicitly defined.
ALTER FUNCTION [dbo].[ProductsUnderThisUnitPrice](@price Money)RETURNS TABLEASRETURN SELECT * FROM Products as P Where p.UnitPrice < @price
Drag to the designer to map the function as follows:
[Function(Name="dbo.ProductsUnderThisUnitPrice",IsComposable=true)]public IQueryable<ProductsUnderThisUnitPriceResult> ProductsUnderThisUnitPrice([Parameter(DbType="Money")]System.Nullable<decimal> price){ return this.CreateMethodCallQuery <ProductsUnderThisUnitPriceResult>(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), price);}
In this case, we can modify the Discontinued attribute to an empty bool type.
private System.Nullable<bool> _Discontinued;public System.Nullable<bool> Discontinued{}
We can call it like this:
var q = from p in db.ProductsUnderThisUnitPrice(10.25M) where !(p.Discontinued ?? false) select p;
The generated SQL statement is as follows:
SELECT [t0].[ProductID], [t0].[ProductName], [t0].[SupplierID], [t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice], [t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel],[t0].[Discontinued]FROM [dbo].[ProductsUnderThisUnitPrice](@p0) AS [t0]WHERE NOT ((COALESCE([t0].[Discontinued],@p1)) = 1)-- @p0: Input Money (Size = 0; Prec = 19; Scale = 4) [10.25]-- @p1: Input Int (Size = 0; Prec = 0; Scale = 0) [0]
4. Use User-Defined Table value functions in join Mode
The above ProductsUnderThisUnitPrice user-defined function is used to call the following:
var q = from c in db.Categories join p in db.ProductsUnderThisUnitPrice(8.50M) on c.CategoryID equals p.CategoryID into prods from p in prods select new { c.CategoryID, c.CategoryName, p.ProductName, p.UnitPrice };
The generated SQL code indicates that the table returned by this function is joined.
SELECT [t0].[CategoryID], [t0].[CategoryName], [t1].[ProductName], [t1].[UnitPrice]FROM [dbo].[Categories] AS [t0]CROSS JOIN [dbo].[ProductsUnderThisUnitPrice](@p0) AS [t1]WHERE ([t0].[CategoryID]) = [t1].[CategoryID]-- @p0: Input Money (Size = 0; Prec = 19; Scale = 4) [8.50]
This series of links: navigation to the LINQ Series
Recommended resources of LINQ
Special topics: http://kb.cnblogs.com/zt/linq/ on all aspects of the entry, advanced, in-depth articles on LINQ.
LINQ group: a good place to learn questions or questions about http://space.cnblogs.com/group/linq.
This article is based on the signature 2.5 mainland China license agreement. You are welcome to reprint, interpret, or use it for commercial purposes. However, you must keep this article's signature Li yongjing (including the link). For more information, see here. If you have any questions or authorization negotiation, please leave a message for me.