Como: usar procedimentos armazenados mapeados para várias formas de resultadoHow to: Use Stored Procedures Mapped for Multiple Result Shapes

Quando um procedimento armazenado pode retornar várias formas de resultado, o tipo de retorno não pode ser fortemente tipado a uma única forma de projeção.When a stored procedure can return multiple result shapes, the return type cannot be strongly typed to a single projection shape. Embora LINQ to SQLLINQ to SQL o possa gerar todos os tipos de projeção possíveis, ele não pode saber a ordem na qual eles serão retornados.Although LINQ to SQLLINQ to SQL can generate all possible projection types, it cannot know the order in which they will be returned.

Compare este cenário com procedimentos armazenados que gerenciar várias formas de resultado seqüencialmente.Contrast this scenario with stored procedures that produce multiple result shapes sequentially. Para obter mais informações, consulte como: usar procedimentos armazenados mapeados para formas de resultados sequenciais.For more information, see How to: Use Stored Procedures Mapped for Sequential Result Shapes.

O atributo de ResultTypeAttribute é aplicado aos procedimentos armazenados que vários tipos de retorno de resultado para especificar o conjunto de tipos podem retornar o procedimento.The ResultTypeAttribute attribute is applied to stored procedures that return multiple result types to specify the set of types the procedure can return.

ExemploExample

No exemplo de código SQL, a forma de resultado depende de entrada (shape =1 ou shape = 2).In the following SQL code example, the result shape depends on the input (shape =1 or shape = 2). Você não sabe que projeção será retornada primeiro.You do not know which projection will be returned first.

CREATE PROCEDURE VariableResultShapes(@shape int)  
AS  
if(@shape = 1)  
    select CustomerID, ContactTitle, CompanyName from customers  
else if(@shape = 2)  
    select OrderID, ShipName from orders  
[Function(Name="dbo.VariableResultShapes")]
[ResultType(typeof(VariableResultShapesResult1))]
[ResultType(typeof(VariableResultShapesResult2))]
public IMultipleResults VariableResultShapes([Parameter(DbType="Int")] System.Nullable<int> shape)
{
    IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), shape);
    return ((IMultipleResults)(result.ReturnValue));
}
<FunctionAttribute(Name:="dbo.VariableResultShapes"), _
ResultType(GetType(VariableResultShapesResult1)), _
ResultType(GetType(VariableResultShapesResult2))> _
Public Function VariableResultShapes(<Parameter(DbType:="Int")> ByVal shape As System.Nullable(Of Integer)) As IMultipleResults
    Dim result As IExecuteResult = Me.ExecuteMethodCall(Me, CType(MethodInfo.GetCurrentMethod, MethodInfo), shape)
    Return CType(result.ReturnValue, IMultipleResults)
End Function

ExemploExample

Você usaria código semelhante ao seguinte para executar este procedimento armazenado.You would use code similar to the following to execute this stored procedure.

Observação

Você deve usar o padrão de GetResult para obter um enumerador do tipo correto, com base no seu conhecimento do procedimento armazenado.You must use the GetResult pattern to obtain an enumerator of the correct type, based on your knowledge of the stored procedure.

Northwnd db = new Northwnd(@"c:\northwnd.mdf");

// Assign the results of the procedure with an argument
// of (1) to local variable 'result'.
IMultipleResults result = db.VariableResultShapes(1);

// Iterate through the list and write results (the company names)
// to the console.
foreach(VariableResultShapesResult1 compName in
    result.GetResult<VariableResultShapesResult1>())
{
    Console.WriteLine(compName.CompanyName);
}

// Pause to view company names; press Enter to continue.
Console.ReadLine();

// Assign the results of the procedure with an argument
// of (2) to local variable 'result'.
IMultipleResults result2 = db.VariableResultShapes(2);

// Iterate through the list and write results (the order IDs)
// to the console.
foreach (VariableResultShapesResult2 ord in
    result2.GetResult<VariableResultShapesResult2>())
{
    Console.WriteLine(ord.OrderID);
}
Dim db As New Northwnd("c:\northwnd.mdf")

' Assign the results of the procedure with an argument
' of (1) to local variable 'result'.
Dim result As IMultipleResults = db.VariableResultShapes(1)

' Iterate through the list and write results (the company name)
' to the console.
For Each compName As VariableResultShapesResult1 _
    In result.GetResult(Of VariableResultShapesResult1)()
    Console.WriteLine(compName.CompanyName)
Next

' Pause to view company names; press Enter to continue.
Console.ReadLine()

' Assign the results of the procedure with an argument
' of (2) to local variable 'result.'
Dim result2 As IMultipleResults = db.VariableResultShapes(2)

' Iterate through the list and write results (the order IDs)
' to the console.
For Each ord As VariableResultShapesResult2 _
    In result2.GetResult(Of VariableResultShapesResult2)()
    Console.WriteLine(ord.OrderID)
Next

Consulte tambémSee also