OData и вставка (AddLink) отношений «многие ко многим» - PullRequest
2 голосов
/ 11 июня 2011

Хорошо, ребята, это сводит меня с ума. Я получил следующую (odata) сущность, которая представляет структуру страницы, в которой каждая страница может иметь детей и родителей. (в основном график, в котором все узлы могут быть связаны). В базе данных она представлена ​​отношением «многие ко многим» с двумя таблицами Page <-> PagePage <-> Page.

Page Entity

Проблема в том, что я просто не могу вставить новую сущность, включая отношение. Последнее, что я попробовал, было:

    Page page = new Page()
    {
        Id = Guid.NewGuid(),
        Title = "New Page",
        Created = DateTime.Now,
        LastChanged = DateTime.Now,
        IsRedirected = false,
        Position = 0,
        Html = "Add your HTML here.",
        Parent = { parent }
    };

    this.Context.AddToPages(page);
    this.Context.AddLink(parent, "Children", page);
    parent.Children.Add(page);
    this.Context.SaveChanges();

Я не могу придумать, что еще можно попробовать. Кто-нибудь взломал этот?

Редактировать 1 : Вот изображение из схемы базы данных: db diagram

Изменить 2 : Сведения об исключении:

System.Data.Services.Client.DataServiceRequestException was unhandled
  Message=An error occurred while processing this request.
  Source=System.Data.Services.Client
  StackTrace:
       at System.Data.Services.Client.DataServiceContext.SaveResult.HandleBatchResponse()
       at System.Data.Services.Client.DataServiceContext.SaveResult.EndRequest()
       at System.Data.Services.Client.DataServiceContext.SaveChanges(SaveChangesOptions options)
       at System.Data.Services.Client.DataServiceContext.SaveChanges()
       at PortfolioManagementConsole.Models.PageViewModel.SaveChanges(Object parameter) in C:\Users\Daniel\documents\visual studio 2010\Projects\PortfolioManagementService\PortfolioManagementConsole\Models\PageViewModel.cs:line 59
       at PortfolioManagementConsole.Common.RelayCommand.Execute(Object parameter) in C:\Users\Daniel\documents\visual studio 2010\Projects\PortfolioManagementService\PortfolioManagementConsole\Common\RelayCommand.cs:line 52
       at MS.Internal.Commands.CommandHelpers.CriticalExecuteCommandSource(ICommandSource commandSource, Boolean userInitiated)
       at System.Windows.Controls.Primitives.ButtonBase.OnClick()
       at System.Windows.Controls.Button.OnClick()
       at Telerik.Windows.Controls.RadButton.OnClick() in c:\Builds\WPF_Scrum\Release_WPF\Sources\Development\Core\Controls\Buttons\RadButton.cs:line 348
       at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
       at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
       at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
       at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
       at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
       at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
       at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
       at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
       at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
       at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
       at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
       at System.Windows.Input.InputManager.ProcessStagingArea()
       at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
       at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
       at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
       at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.Run()
       at System.Windows.Application.RunDispatcher(Object ignore)
       at System.Windows.Application.RunInternal(Window window)
       at System.Windows.Application.Run(Window window)
       at System.Windows.Application.Run()
       at PortfolioManagementConsole.App.Main() in C:\Users\Daniel\documents\visual studio 2010\Projects\PortfolioManagementService\PortfolioManagementConsole\obj\x86\Debug\App.g.cs:line 0
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.Data.Services.Client.DataServiceClientException
       Message=<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
  <code></code>
  <message xml:lang="de-CH">An error occurred while processing this request.</message>
</error>
       Source=System.Data.Services.Client
       StatusCode=500
       StackTrace:
            at System.Data.Services.Client.DataServiceContext.SaveResult.<HandleBatchResponse>d__1e.MoveNext()
       InnerException: 

1 Ответ

0 голосов
/ 13 ноября 2011

Ваш сервер служб данных WCF не возвращает подробные сообщения об ошибках, и это не помогает вам точно определить сообщение об ошибке, возвращаемое с сервера. Следуйте этим инструкциям, чтобы включить подробные сообщения об ошибках с сервера: http://blogs.msdn.com/b/phaniraj/archive/2008/06/18/debugging-ado-net-data-services.aspx. После того, как вы включите это, вы сможете увидеть сообщение об ошибке, выдаваемое сервером.

При просмотре вашей модели вам нужна еще одна ссылка от ребенка обратно к родителю. Добавьте эту строку в код прямо перед SaveChanges:

this.Context.SetLink (page, "Parent", parent);

Чтобы лучше понять это, вот несколько ссылок в моем блоге, где я подробно описываю, как работать с ассоциациями с помощью клиента служб данных WCF:

1 ко многим ассоциациям

http://blogs.msdn.com/b/phaniraj/archive/2008/10/23/working-with-associations-in-ado-net-data-services-part-2.aspx

1 к 1 ассоциациям

http://blogs.msdn.com/b/phaniraj/archive/2008/07/02/working-with-relations-in-ado-net-data-services-beta-1.aspx

...