データ サービスにエンティティが既に存在する場合、クエリを最初に実行することなく、WCF Data Services クライアント ライブラリを使用して、エンティティを表すオブジェクトを DataServiceContext に直接アタッチできます。 詳細については、「データ サービスの更新 (WCF Data Services)」を参照してください。
このトピックの例では、Northwind サンプル データ サービスおよび自動生成されたクライアント データ サービス クラスを使用します。 このサービスおよびクライアント データ クラスは、WCF Data Services クイック スタートを完了したときに作成されます。
例
次の例は、データ サービスに保存する変更を含む既存の Customer
オブジェクトを作成する方法を示します。 オブジェクトがコンテキストにアタッチされ、SaveChanges メソッドが呼び出される前に、UpdateObject メソッドが呼び出されてアタッチされたオブジェクトが Modified としてマークされます。
' 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);
}