Размещение связанных объектов в WCF Rest
Я разработал пример службы REST WCF, которая принимает объект, который создает объект "Порядок", реализация метода, как показано ниже:
[Description("Updates an existing order")]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, UriTemplate = "/Orders")]
[OperationContract]
public void UpdateOrder(Order order)
{
try
{
using (var context = new ProductsDBEntities())
{
context.Orders.Attach(order);
context.ObjectStateManager.ChangeObjectState(order, System.Data.EntityState.Modified);
context.SaveChanges();
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "Order updated successfully.";
}
}
catch (Exception ex)
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError;
WebOperationContext.Current.OutgoingResponse.StatusDescription = ex.Message + " " + ((ex.InnerException != null) ? ex.InnerException.Message : string.Empty);
}
}
Я пытаюсь использовать эту службу на клиенте, используя сборки WCF Rest Starter Kit. Код на стороне клиента для использования сервиса, как показано ниже:
var order = new Order(){
OrderId = Convert.ToInt32(ddlCategories.SelectedItem.Value)
};
order.Order_X_Products.Add(new Order_X_Products { ProductId = 1, Quantity = 10});
order.Order_X_Products.Add(new Order_X_Products { ProductId = 2, Quantity = 10});
var content = HttpContentExtensions.CreateJsonDataContract<Order>(order);
var updateResponse = client.Post("Orders", content);
Нижняя строка
var updateResponse = client.Post("Orders", content);
выдает следующую ошибку:
Server Error in '/' Application.
Specified argument was out of the range of valid values.
Parameter name: value
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: value
У меня похожая логика для создания заказа и он работает нормально.
Я также попытался, удалив следующие строки
order.Order_X_Products.Add(new Order_X_Products { ProductId = 1, Quantity = 10});
order.Order_X_Products.Add(new Order_X_Products { ProductId = 2, Quantity = 10});
но все та же ошибка.
Пожалуйста, помогите мне решить эту проблему.
Я также попытался сериализовать объект Order в XML и изменить RequestFormat метода UpdateOrder на XML. В этом случае я получаю следующую ошибку, если какие-либо связанные объекты заполнены.
Server Error in '/' Application.
Object graph for type 'WcfRestSample.Models.Common.Order_X_Products' contains cycles and cannot be serialized if reference tracking is disabled.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Runtime.Serialization.SerializationException: Object graph for type 'WcfRestSample.Models.Common.Order_X_Products' contains cycles and cannot be serialized if reference tracking is disabled.
Source Error:
Line 102:
Line 103: var content = HttpContentExtensions.CreateDataContract<Order> (order);
Line 104: var updateResponse = client.Post("Orders", content);
Line 105:
Line 106:
Я хочу "обновить" заказ вместе со связанными "продуктами" через таблицу сопоставления "Order_X_Products".
1 ответ
Здесь есть пост http://smehrozalam.wordpress.com/2010/10/26/datacontractserializer-working-with-class-inheritence-and-circular-references/ котором рассказывается, как работать с циклическими ссылками при использовании DataContractSerializer.,