Как определять связи сущностей (службы WCF Data Services)
После добавления новой сущности в службах Службы WCF Data Services связи между нею и связанными сущностями не определяются автоматически. Пользователь может создать и изменить связи между экземплярами сущностей и отразить эти изменения в службе данных с помощью клиентской библиотеки. Дополнительные сведения см. в разделе Обновление службы данных (службы WCF Data Services).
Пример в этом разделе использует образец службы данных Northwind и автоматически сформированные клиентские классы службы данных. Эта служба и клиентские классы данных создаются после выполнения действий, описанных в разделе Краткое руководство по службам WCF Data Services.
Пример
В следующем примере создается новый экземпляр объекта и вызывается метод AddRelatedObject контекста DataServiceContext для создания в контексте нового элемента и ссылки на связанный с ним заказ. Сообщение HTTP POST отправляется в службу данных при вызове метода SaveChanges.
Dim productId = 25
Dim customerId = "ALFKI"
Dim newItem As Order_Detail = Nothing
' Create the DataServiceContext using the service URI.
Dim context = New NorthwindEntities(svcUri)
Try
' Get the specific product.
Dim selectedProduct = (From product In context.Products _
Where product.ProductID = productId _
Select product).Single()
' Get the specific customer.
Dim cust = (From customer In context.Customers.Expand("Orders") _
Where customer.CustomerID = customerId _
Select customer).Single()
' Get the first order.
Dim order = cust.Orders.FirstOrDefault()
' Create a new order detail for the specific product.
newItem = Order_Detail.CreateOrder_Detail( _
order.OrderID, selectedProduct.ProductID, 10, 5, 0)
' Add the new item with a link to the related order.
context.AddRelatedObject(order, "Order_Details", newItem)
' Since the item is now tracked by the context,
' set just the link to the related product.
context.AddLink(selectedProduct, "Order_Details", newItem)
' Add the new order detail to the collection, and
' set the reference to the product.
order.Order_Details.Add(newItem)
newItem.Order = order
newItem.Product = selectedProduct
' Send the inserts to the data service.
context.SaveChanges()
Catch ex As DataServiceQueryException
Throw New ApplicationException( _
"An error occurred when saving changes.", ex)
' Handle any errors that may occur during insert, such as
' a constraint violation.
Catch ex As DataServiceRequestException
Throw New ApplicationException( _
"An error occurred when saving changes.", ex)
int productId = 25;
string customerId = "ALFKI";
Order_Detail newItem = null;
// Create the DataServiceContext using the service URI.
NorthwindEntities context = new NorthwindEntities(svcUri);
try
{
// Get the specific product.
var selectedProduct = (from product in context.Products
where product.ProductID == productId
select product).Single();
// Get the specific customer.
var cust = (from customer in context.Customers.Expand("Orders")
where customer.CustomerID == customerId
select customer).Single();
// Get the first order.
Order order = cust.Orders.FirstOrDefault();
// Create a new order detail for the specific product.
newItem = Order_Detail.CreateOrder_Detail(
order.OrderID, selectedProduct.ProductID, 10, 5, 0);
// Add the new item with a link to the related order.
context.AddRelatedObject(order, "Order_Details", newItem);
// Since the item is now tracked by the context,
// set just the link to the related product.
context.AddLink(selectedProduct, "Order_Details", newItem);
// Add the new order detail to the collection, and
// set the reference to the product.
order.Order_Details.Add(newItem);
newItem.Order = order;
newItem.Product = selectedProduct;
// Send the inserts to the data service.
context.SaveChanges();
}
catch (DataServiceQueryException ex)
{
throw new ApplicationException(
"An error occurred when saving changes.", ex);
}
// Handle any errors that may occur during insert, such as
// a constraint violation.
catch (DataServiceRequestException ex)
{
throw new ApplicationException(
"An error occurred when saving changes.", ex);
}
Следующий пример иллюстрирует использование метода AddObject для добавления объекта Order_Details
к связанному объекту Orders
со ссылкой на конкретный объект Products
. Методы AddLink и SetLink определяют связи. В этом примере также явно заданы свойства навигации объекта Order_Details
.
Dim productId = 25
Dim customerId = "ALFKI"
Dim newItem As Order_Detail = Nothing
' Create the DataServiceContext using the service URI.
Dim context = New NorthwindEntities(svcUri)
Try
' Get the specific product.
Dim selectedProduct = (From product In context.Products _
Where product.ProductID = productId _
Select product).Single()
' Get the specific customer.
Dim cust = (From customer In context.Customers.Expand("Orders") _
Where customer.CustomerID = customerId _
Select customer).Single()
' Get the first order.
Dim order = cust.Orders.FirstOrDefault()
' Create a new order detail for the specific product.
newItem = Order_Detail.CreateOrder_Detail( _
order.OrderID, selectedProduct.ProductID, 10, 5, 0)
' Add the new order detail to the context.
context.AddToOrder_Details(newItem)
' Add links for the one-to-many relationships.
context.AddLink(order, "Order_Details", newItem)
context.AddLink(selectedProduct, "Order_Details", newItem)
' Add the new order detail to the collection, and
' set the reference to the product.
order.Order_Details.Add(newItem)
newItem.Product = selectedProduct
' Send the inserts to the data service.
context.SaveChanges()
Catch ex As DataServiceQueryException
Throw New ApplicationException( _
"An error occurred when saving changes.", ex)
' Handle any errors that may occur during insert, such as
' a constraint violation.
Catch ex As DataServiceRequestException
Throw New ApplicationException( _
"An error occurred when saving changes.", ex)
int productId = 25;
string customerId = "ALFKI";
Order_Detail newItem = null;
// Create the DataServiceContext using the service URI.
NorthwindEntities context = new NorthwindEntities(svcUri);
try
{
// Get the specific product.
var selectedProduct = (from product in context.Products
where product.ProductID == productId
select product).Single();
// Get the specific customer.
var cust = (from customer in context.Customers.Expand("Orders")
where customer.CustomerID == customerId
select customer).Single();
// Get the first order.
Order order = cust.Orders.FirstOrDefault();
// Create a new order detail for the specific product.
newItem = Order_Detail.CreateOrder_Detail(
order.OrderID, selectedProduct.ProductID, 10, 5, 0);
// Add the new order detail to the context.
context.AddToOrder_Details(newItem);
// Add links for the one-to-many relationships.
context.AddLink(order, "Order_Details", newItem);
context.AddLink(selectedProduct, "Order_Details", newItem);
// Add the new order detail to the collection, and
// set the reference to the product.
order.Order_Details.Add(newItem);
newItem.Product = selectedProduct;
// Send the inserts to the data service.
context.SaveChanges();
}
catch (DataServiceQueryException ex)
{
throw new ApplicationException(
"An error occurred when saving changes.", ex);
}
// Handle any errors that may occur during insert, such as
// a constraint violation.
catch (DataServiceRequestException ex)
{
throw new ApplicationException(
"An error occurred when saving changes.", ex);
}
См. также
Задачи
Как добавлять, изменять и удалять сущности (службы WCF Data Services)