Share via


방법: DataServiceContext에 기존 엔터티 연결(WCF Data Services)

데이터 서비스에 엔터티가 이미 있으면 WCF Data Services 클라이언트 라이브러리에서 먼저 쿼리를 실행하지 않고 엔터티를 나타내는 개체를 DataServiceContext에 직접 연결할 수 있습니다. 자세한 내용은 데이터 서비스 업데이트(WCF Data Services)를 참조하십시오.

이 항목의 예제에서는 Northwind 샘플 데이터 서비스 및 자동 생성된 클라이언트 데이터 서비스 클래스를 사용합니다. 이 서비스 및 클라이언트 데이터 클래스는 WCF Data Services 퀵 스타트를 완료하면 만들어집니다.

예제

다음 예제에서는 데이터 서비스에 저장될 변경 내용이 포함되어 있는 기존 Customer 개체를 만드는 방법을 보여 줍니다. 개체가 컨텍스트에 연결되고 UpdateObject 메서드가 호출되어 SaveChanges 메서드를 호출하기 전에 연결된 개체를 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);
}

참고 항목

기타 리소스

WCF Data Services 클라이언트 라이브러리