2009-09-08 2 views
0

Я читал this учебник о том, как реализовать приложение Silverlight. Учебник использует базу данных Northwind для своих примеров. Я использую образцы кода для реализации той же функциональности, что и учебник, в моем собственном приложении с моей собственной базой данных. В последней части учебника показано, как добавлять новые элементы и связанные с ними отношения в определенные таблицы в базе данных Northwind. Данный пример демонстрирует эту функцию на 3 связанных таблиц (продукта, заказ, order_details), используя приведенный ниже код:Silverlight Asynchronous Crud Insert: отношения «один-к-одному»?

private void addDetail_Click(object sender, RoutedEventArgs e) 
{ 
    // Define a URI that returns the product with the specified ID. 
    Uri productUri = new Uri(svcContext.BaseUri.AbsoluteUri 
     + "/Products(" + this.productId.Text + ")"); 

    // Begin a query operation retrieve the Product object 
    // that is required to add a link to the new Order_Detail. 
    svcContext.BeginExecute<Products>(productUri, 
     OnProductQueryCompleted, null); 
} 

private void OnProductQueryCompleted(IAsyncResult result) 
{ 
    // Use the Dispatcher to ensure that the 
    // asynchronous call returns in the correct thread. 
    Dispatcher.BeginInvoke(() => 
     { 
      // Get the Product returned by the completed query. 
      IEnumerable<Products> queryResult = 
       svcContext.EndExecute<Products>(result); 
      Products returnedProduct = queryResult.First(); 

      // Get the currently selected order. 
      Orders currentOrder = (Orders)ordersGrid.SelectedItem; 

      // Create a new Order_Details object with the supplied FK values. 
      Order_Details newItem = Order_Details.CreateOrder_Details(currentOrder.OrderID, 
       returnedProduct.ProductID, 0, 0, 0); 

      detailsBindingCollection.Add(newItem); 

      // Add the new item to the context. 
      svcContext.AddToOrder_Details(newItem); 

      // Add the relationship between the order and the new item. 
      currentOrder.Order_Details.Add(newItem); 
      svcContext.AddLink(currentOrder, "Order_Details", newItem); 

      // Set the reference to the order and product from the item. 
      newItem.Orders = currentOrder; 
      svcContext.SetLink(newItem, "Orders", currentOrder); 

      // Add the relationship between the product and the new item. 
      returnedProduct.Order_Details.Add(newItem); 
      svcContext.AddLink(returnedProduct, "Order_Details", newItem); 

      // Set the reference to the product from the item. 
      newItem.Products = returnedProduct; 
      svcContext.SetLink(newItem, "Products", returnedProduct); 
     } 
    ); 
} 

Мои базы данных Сценарии:

CREATE TABLE InmarsatZenith.dbo.ClientJob 
(JobRef nvarchar(15), 
Summary text 
PRIMARY KEY(JobRef)) 

CREATE TABLE InmarsatZenith.dbo.Job 
(IntRef uniqueidentifier, 
JobRef nvarchar(15), 
CopyDeadline datetime, 
PublicationDate datetime, 
Repeat bit, 
BusinessType nvarchar(25), 
Sector nvarchar(30), 
Lang nvarchar(15), 
Format nvarchar(25), 
CreativeRotation nvarchar(50), 
TipinType nvarchar(25), 
Status nvarchar(100) 
PRIMARY KEY(IntRef)) 

CREATE TABLE InmarsatZenith.dbo.Detail 
(IntRef uniqueidentifier, 
Description nvarchar(100), 
Date datetime 
PRIMARY KEY(IntRef)) 

Существует связь один-ко-многим между задание клиента и работа (1 клиентское задание может иметь много заданий). И взаимное отношение между работой и деталями.

Проблема заключается в том, что я хочу реализовать те же асинхронные методы в моем приложении, но для гораздо более простой взаимосвязи. Поэтому по существу я хочу добавить новое задание в таблицу «Job», а затем добавить связанные детали в таблицу «Job Details». У меня были некоторые проблемы с попыткой конвертировать этот образец кода, чтобы работать с этим конкретным методом, и я бы очень признателен за помощь в адаптации этого кода, чтобы работать для отношения «один к одному».

Если бы кто-нибудь мог просветить меня по этому вопросу, я был бы очень признателен.

С уважением, спасибо заранее.

ответ

Смежные вопросы