此示例代码主要示范如何将用户在SQL Server中定义的表值函数映射到对象模型中的函数,并是示范了如何调用这样的映射函数。
示范中用到的表值函数定义如下:
CREATE FUNCTION ProductsCostingMoreThan(@Cost money)
RETURNS TABLE
AS
RETURN
SELECT ProductID, UnitPrice
FROM Products
WHERE UnitPrice > @Cost
使用如下的方式来映射表值函数,特别需要注意的是,此次返回的是IQueryable<TEntity>,并且其内部调用的是DataContext.CreateMethodCallQuery(),而不是DataContext.ExecuteMethodCall()。
[Function(Name="dbo.ProductsCostingMoreThan", IsComposable=true)]
public IQueryable<ProductsCostingMoreThanResult> ProductsCostingMoreThan(
[Parameter(Name="Cost", DbType="Money")] System.Nullable<decimal> cost)
{
return this.CreateMethodCallQuery<ProductsCostingMoreThanResult>(this,
((MethodInfo)(MethodInfo.GetCurrentMethod())), cost);
}
可以使用类似如下的方式调用上面创建的映射函数。本示例中是将表值函数的查询结果作为LINQ查询的数据源来使用,并且进行了链接查询。
NorthwindDataContext db = new NorthwindDataContext(@"C:/LINQ/Northwind.mdf");
var PartialProducts =
from P1 in db.ProductsCostingMoreThan(80.50m)
join P2 in db.Products on P1.ProductID equals P2.ProductID
select new
{
P1.ProductID,
P2.UnitPrice
};
foreach (var ProductObject in PartialProducts)
{
Console.WriteLine("ProductID={0} UnitPrice={1}",
ProductObject.ProductID,
ProductObject.UnitPrice);
Thread.Sleep(100);
}