Я поддерживаю приложение WPF. Я создал базу данных с использованием Entity Framework Code First, и теперь я хотел бы использовать мою базу данных с моим графическим интерфейсом. У меня есть ListBox в xaml
Привязать список к таблице базы данных
XAML
<Window.Resources>
<DataTemplate x:Key="lstDishesTemplate">
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path = Dishes.Description}" FontWeight="Bold"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</Window.Resources>
<ListBox x:Name="lstDishes" Height="415" VerticalAlignment="Bottom" Margin="0,0,1032,42" HorizontalAlignment="Right" Width="281" ItemTemplate="{StaticResource lstDishesTemplate}" Background="#FFDDC9B0" BorderBrush="{x:Null}"/>
И тогда я пытаюсь запросить мои данные в таблицу, как это:
XAML.cs
private void Window_Loaded(object sender, RoutedEventArgs e)
{
public PizzeriaDBContext db = new PizzeriaDBContext();
var dish = db.Dishes.ToList();
lstDishes.ItemsSource = dish;
}
Я получаю исключение:
An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in EntityFramework.SqlServer.dll
Additional information: Exception generated by destination of a call (translated).
Update:
System.Reflection.TargetInvocationException was unhandled
HResult=-2146232828
Message=Eccezione generata dalla destinazione di una chiamata.
Source=mscorlib
StackTrace:
in System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
in System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
in System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
in System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslateColumnMap(Translator translator, Type elementType, ColumnMap columnMap, MetadataWorkspace workspace, SpanIndex spanIndex, MergeOption mergeOption, Boolean streaming, Boolean valueLayer)
in System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory.Prepare(ObjectContext context, DbQueryCommandTree tree, Type elementType, MergeOption mergeOption, Boolean streaming, Span span, IEnumerable`1 compiledQueryParameters, AliasGenerator aliasGenerator)
in System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
in System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()
in System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
in System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
in System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
in System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
in System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
in System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
in System.Collections.ObjectModel.ObservableCollection`1.CopyFrom(IEnumerable`1 collection)
in System.Collections.ObjectModel.ObservableCollection`1..ctor(IEnumerable`1 collection)
in Cw2.ServerWin.Window_Loaded(Object sender, RoutedEventArgs e) in C:\Users\Fennec\Documents\assessment2\Cw2\Server.xaml.cs:riga 56
in System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
in System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
in System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
in System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
in System.Windows.BroadcastEventHelper.BroadcastEvent(DependencyObject root, RoutedEvent routedEvent)
in System.Windows.BroadcastEventHelper.BroadcastLoadedEvent(Object root)
in MS.Internal.LoadedOrUnloadedOperation.DoWork()
in System.Windows.Media.MediaContext.FireLoadedPendingCallbacks()
in System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
in System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
in System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
in System.Windows.Media.MediaContext.Resize(ICompositionTarget resizedCompositionTarget)
in System.Windows.Interop.HwndTarget.OnResize()
in System.Windows.Interop.HwndTarget.HandleMessage(WindowMessage msg, IntPtr wparam, IntPtr lparam)
in System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
in MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
in MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
in System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
in System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
in System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
in MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
InnerException:
HResult=-2146233079
Message=The class 'Cw2.Dish' has no parameterless constructor.
Source=EntityFramework
StackTrace:
in System.Data.Entity.Core.Objects.DelegateFactory.GetConstructorForType(Type type)
in System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslatorVisitor.Emit_ConstructEntity(EntityType oSpaceType, IEnumerable`1 propertyBindings, Expression entityKeyReader, Expression entitySetReader, TranslatorArg arg, EntityProxyTypeInfo proxyTypeInfo)
in System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslatorVisitor.Visit(EntityColumnMap columnMap, TranslatorArg arg)
in System.Data.Entity.Core.Query.InternalTrees.EntityColumnMap.Accept[TResultType,TArgType](ColumnMapVisitorWithResults`2 visitor, TArgType arg)
in System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslatorVisitor.ProcessCollectionColumnMap(CollectionColumnMap columnMap, TranslatorArg arg, ColumnMap discriminatorColumnMap, Object discriminatorValue)
in System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslatorVisitor.Visit(SimpleCollectionColumnMap columnMap, TranslatorArg arg)
in System.Data.Entity.Core.Query.InternalTrees.SimpleCollectionColumnMap.Accept[TResultType,TArgType](ColumnMapVisitorWithResults`2 visitor, TArgType arg)
in System.Data.Entity.Core.Common.Internal.Materialization.Translator.TranslateColumnMap[T](ColumnMap columnMap, MetadataWorkspace workspace, SpanIndex spanIndex, MergeOption mergeOption, Boolean streaming, Boolean valueLayer)
InnerException:
ОТВЕТ
Анализ полного исключения, кажется, что классы конструкторы не должны иметь параметры.
Я по-прежнему получаю то же исключение – Koosshh56
Вы хотите увидеть мой класс блюд? – Koosshh56
Но я включил исключение, которое я получил в своем вопросе. Необработанное исключение типа «System.Reflection.TargetInvocationException» произошло в EntityFramework.SqlServer.dll Дополнительная информация: Исключение, сгенерированное при назначении вызова (переведено). – Koosshh56