Linq有很多值得学习的地方,这里我们主要介绍Linq结果集形状,包括介绍 ResultTypeAttribute 属性适用于返回多个结果类型的存储过程等方面。
当存储过程可以返回多个Linq结果集形状时,返回类型无法强类型化为单个投影形状。尽管 LINQ to SQL 可以生成所有可能的投影类型,但它无法获知将以何种顺序返回它们。 ResultTypeAttribute 属性适用于返回多个结果类型的存储过程,用以指定该过程可以返回的类型的集合。
在下面的 SQL 代码示例中,Linq结果集形状取决于输入(param1 = 1或param1 = 2)。我们不知道先返回哪个投影。
ALTER PROCEDURE [dbo].[SingleRowset_MultiShape]
-- Add the parameters for the stored procedure here
(@param1 int )
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
if(@param1 = 1)
SELECT * from Customers as c where c.Region = 'WA'
else if (@param1 = 2)
SELECT CustomerID, ContactName, CompanyName from
Customers as c where c.Region = 'WA'
END
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
拖到O/R设计器内,它自动生成了以下代码段:
[Function(Name="dbo.[Whole Or Partial Customers Set]")]
public ISingleResult<Whole_Or_Partial_Customers_SetResult>
Whole_Or_Partial_Customers_Set([Parameter(DbType="Int")]
System.Nullable<int> param1)
{
IExecuteResult result = this.ExecuteMethodCall(this,
((MethodInfo)(MethodInfo.GetCurrentMethod())), param1);
return ((ISingleResult<Whole_Or_Partial_Customers_SetResult>)
(result.ReturnValue));
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
但是,VS2008会把多结果集存储过程识别为单结果集的存储过程,默认生成的代码我们要手动修改一下,要求返回多个结果集,像这样:
[Function(Name="dbo.[Whole Or Partial Customers Set]")]
[ResultType(typeof(WholeCustomersSetResult))]
[ResultType(typeof(PartialCustomersSetResult))]
public IMultipleResults Whole_Or_Partial_Customers_Set([Parameter
(DbType="Int")] System.Nullable<int> param1)
{
IExecuteResult result = this.ExecuteMethodCall(this,
((MethodInfo)(MethodInfo.GetCurrentMethod())), param1);
return ((IMultipleResults)(result.ReturnValue));
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
我们分别定义了两个分部类,用于指定返回的类型。这样就可以使用了,下面代码直接调用,分别返回各自的结果集合。
//返回全部Customer结果集
IMultipleResults result = db.Whole_Or_Partial_Customers_Set(1);
IEnumerable<WholeCustomersSetResult> shape1 =
result.GetResult<WholeCustomersSetResult>();
foreach (WholeCustomersSetResult compName in shape1)
{
Console.WriteLine(compName.CompanyName);
}
//返回部分Customer结果集
result = db.Whole_Or_Partial_Customers_Set(2);
IEnumerable<PartialCustomersSetResult> shape2 =
result.GetResult<PartialCustomersSetResult>();
foreach (PartialCustomersSetResult con in shape2)
{
Console.WriteLine(con.ContactName);
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
语句描述:这个实例使用存储过程返回“WA”地区中的一组客户。返回的Linq结果集形状取决于传入的参数。如果参数等于 1,则返回所有客户属性。如果参数等于2,则返回ContactName属性。
【编辑推荐】