Share via


DataServiceContext.UpdateObject(Object) 方法

定義

DataServiceContext 中指定之物件的狀態變更成 Modified

public:
 void UpdateObject(System::Object ^ entity);
public void UpdateObject (object entity);
member this.UpdateObject : obj -> unit
Public Sub UpdateObject (entity As Object)

參數

entity
Object

要指派為 Modified 狀態的已追蹤實體。

例外狀況

entitynull 時。

entity 處於 Detached 狀態時。

範例

下列範例會擷取並修改現有的物件,然後呼叫 UpdateObjectDataServiceContext 方法,將內容中的項目標記為已更新。 呼叫 SaveChanges 時,HTTP MERGE 訊息會傳送到資料服務。 此範例會DataServiceContext根據 Northwind 數據服務使用 Add Service Reference 工具所產生的 ,這是在您完成 WCF Data Services 時所建立的 。

string customerId = "ALFKI";

// Create the DataServiceContext using the service URI.
NorthwindEntities context = new NorthwindEntities(svcUri);

// Get a customer to modify using the supplied ID.
var customerToChange = (from customer in context.Customers
                        where customer.CustomerID == customerId
                        select customer).Single();

// Change some property values.
customerToChange.CompanyName = "Alfreds Futterkiste";
customerToChange.ContactName = "Maria Anders";
customerToChange.ContactTitle = "Sales Representative";

try
{
    // Mark the customer as updated.
    context.UpdateObject(customerToChange);

    // Send the update to the data service.
    context.SaveChanges();
}
catch (DataServiceRequestException  ex)
{
    throw new ApplicationException(
        "An error occurred when saving changes.", ex);
}
Dim customerId = "ALFKI"

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

' Get a customer to modify using the supplied ID.
Dim customerToChange = (From customer In context.Customers _
                        Where customer.CustomerID = customerId _
                        Select customer).Single()

' Change some property values.
customerToChange.CompanyName = "Alfreds Futterkiste"
customerToChange.ContactName = "Maria Anders"
customerToChange.ContactTitle = "Sales Representative"

Try
    ' Mark the customer as updated.
    context.UpdateObject(customerToChange)

    ' Send the update to the data service.
    context.SaveChanges()
Catch ex As DataServiceRequestException
    Throw New ApplicationException( _
            "An error occurred when saving changes.", ex)
End Try

適用於