通过仅使用存储过程自定义操作

通过仅使用存储过程来访问数据是常见的情况。

示例

说明

通过使用存储过程来自定义操作中提供的示例中,你甚至可以将第一个查询(导致动态 SQL 执行)替换为包装了存储过程的方法调用,通过这种方法来修改此示例。

假定 CustomersByCity 就是此方法,如下面的示例所示。

代码

[Function()]
public IEnumerable<Customer> CustomersByCity(
    [Parameter(Name = "City", DbType = "NVarChar(15)")]
    string city)
{
    IExecuteResult result = this.ExecuteMethodCall(this,
        ((MethodInfo)(MethodInfo.GetCurrentMethod())),
        city);
    return ((IEnumerable<Customer>)(result.ReturnValue));
}
<[Function]()> _
Public Function CustomersByCity( _
    <Parameter(Name:="City", DbType:="NVarChar(15)")> ByVal _
        city As String) As IEnumerable(Of Customer)

    Dim result = Me.ExecuteMethodCall(Me, _
        (CType(MethodInfo.GetCurrentMethod(), IEnumerable(Of  _
        Customer))), city)
    Return CType(result.ReturnValue, IEnumerable(Of Customer))
End Function

下面的代码不用任何动态 SQL 即可执行。

NorthwindThroughSprocs db = new NorthwindThroughSprocs("...");
// Use a method call (stored procedure wrapper) instead of
// a LINQ query against the database.
var custQuery =
    db.CustomersByCity("London");

foreach (Customer custObj in custQuery)
{
    // Deferred loading of custObj.Orders uses the override
    // LoadOrders. There is no dynamic SQL.
    foreach (Order ord in custObj.Orders)
    {
        // Make some changes to customers/orders.
        // Overrides for Customer are called during the execution
        // of the following.
    }
}
db.SubmitChanges();
Dim db As New Northwind("...")
' Use a method call (stored procedure wrapper) instead of
' a LINQ query against the database.
Dim custQuery = db.CustomersByCity("London")

For Each custObj In custQuery
    ' Deferred loading of custObj.Orders uses the override
    ' LoadOrders. There is no dynamic SQL.

    For Each ord In custObj.Orders
        ' Make some changes to customers/orders.
        ' Overrides for Customer are called during the execution
        ' of the following:
        db.SubmitChanges()
    Next
Next

请参阅