共用方式為


HOW TO:將現有的實體附加至 DataServiceContext (WCF Data Services)

若實體已經存在資料服務中,WCF Data Services 用戶端程式庫可讓您將代表該實體的物件直接附加至 DataServiceContext,且不需先執行查詢。 如需詳細資訊,請參閱更新資料服務 (WCF Data Services)

本主題的範例使用 Northwind 範例資料服務,以及自動產生的用戶端資料服務類別。 此服務和用戶端資料類別會在您完成 WCF Data Services 快速入門時建立。

範例

下列範例示範如何建立現有的 Customer 物件,此物件包含要儲存至資料服務的變更。 系統會將物件附加至內容,並呼叫 UpdateObject 方法,將附加物件標記為 Modified,然後再呼叫 SaveChanges 方法。

' Create the DataServiceContext using the service URI.
Dim context = New NorthwindEntities(svcUri)

' Define an existing customer to attach, including the key.
Dim customer As Customer = _
    customer.CreateCustomer("ALFKI", "Alfreds Futterkiste")

' Set current property values.
customer.Address = "Obere Str. 57"
customer.City = "Berlin"
customer.PostalCode = "12209"
customer.Country = "Germany"

' Set property values to update.
customer.ContactName = "Peter Franken"
customer.ContactTitle = "Marketing Manager"
customer.Phone = "089-0877310"
customer.Fax = "089-0877451"

Try
    ' Attach the existing customer to the context and mark it as updated.
    context.AttachTo("Customers", customer)
    context.UpdateObject(customer)

    ' Send updates to the data service.
    context.SaveChanges()
Catch ex As DataServiceClientException
    Throw New ApplicationException( _
            "An error occurred when saving changes.", ex)
End Try
// Create the DataServiceContext using the service URI.
NorthwindEntities context = new NorthwindEntities(svcUri);

// Define an existing customer to attach, including the key.
Customer customer = 
    Customer.CreateCustomer("ALFKI", "Alfreds Futterkiste");

// Set current property values.
customer.Address = "Obere Str. 57";
customer.City = "Berlin";
customer.PostalCode = "12209";
customer.Country = "Germany";

// Set property values to update.
customer.ContactName = "Peter Franken";
customer.ContactTitle = "Marketing Manager";
customer.Phone = "089-0877310";
customer.Fax = "089-0877451";

try
{
    // Attach the existing customer to the context and mark it as updated.
    context.AttachTo("Customers", customer);
    context.UpdateObject(customer);

    // Send updates to the data service.
    context.SaveChanges();
}
catch (DataServiceClientException ex)
{
    throw new ApplicationException(
        "An error occurred when saving changes.", ex);
}

另請參閱

其他資源

WCF Data Services 用戶端程式庫