0
点赞
收藏
分享

微信扫一扫

[代码]如何使用用户定义的标量值函数(LINQ to SQL)


此示例代码主要用来示范如何在LINQ to SQL的对象模型中生成映射到SQL用户定义的标量值函数的函数。
SQL Server的标量值函数通常类似与如下的定义:

CREATE FUNCTION ReverseCustName(@CustomerID nchar(5))
RETURNS nvarchar(30)
AS
BEGIN
    DECLARE @CustomerName nvarchar(30)
    SELECT @CustomerName = [ContactName] FROM [Customers]
  WHERE [CustomerID] = @CustomerID
    RETURN @CustomerName
END


诸如如上所定义的标量值函数,可以通过下面的做法将其映射到对象模型中的函数。
特别需要注意的是FunctionAttribute.IsComposable必须设置为true,如果为false则表示映射的是存储过程,而不是用户自定义函数。

[Function(Name="dbo.ReverseCustName", IsComposable=true)]
public string ReverseCustomerName(
    [Parameter(Name="CustomerID", DbType="NChar(5)")]string CustomerID)
{
    IExecuteResult Result = this.ExecuteMethodCall(this,
        (MethodInfo)MethodInfo.GetCurrentMethod(),
        CustomerID);
    return (string)Result.ReturnValue;
}


接着就可以通过类似如下的代码来调用上面定义的映射函数,从而达到调用数据库中用户自定义的标量值函数的目的。
在这个代码中,则是通过客户的编号获取客户的联系名。然后将其打印到控制台上。

NorthwindDataContext db = new NorthwindDataContext(@"C:/LINQ/Northwind.mdf");
string CustomerName = db.ReverseCustomerName("ALFKI");
Console.WriteLine(CustomerName);

举报

相关推荐

0 条评论