共用方式為


僅使用預存程序自訂作業 (LINQ to SQL)

在常見的案例中使用預存程序存取資料。

範例

說明

您甚至可以使用包裝預存程序的方法呼叫來取代第一個查詢 (它會造成動態 SQL 執行),進而修改 使用預存程序自訂作業 (LINQ to SQL) 中提供的範例。

假設 CustomersByCity 為下列範例中的方法。

程式碼

<[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
[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));
}

下列程式碼會在沒有任何動態 SQL 的情況下執行。

Dim db As New Northwnd("...")
' 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
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();

請參閱

概念

開發人員覆寫預設行為的責任 (LINQ to SQL)