简体   繁体   中英

Bind listbox to database table

I'm buinding a WPF application. I've created the database using Entity Framework Code First and now I would like to use my database with my GUI. I have a listbox in 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}"/>

And then I'm trying to query my data in the table like this:

XAML.cs

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    public PizzeriaDBContext db = new PizzeriaDBContext();

    var dish = db.Dishes.ToList();
    lstDishes.ItemsSource = dish;
}

I'm getting an exception:

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: 

ANSWER

Analyzing full exception, it seems that classes constructors must not have parameters.

At first:

The inner exception says your error:

Message=The class 'Cw2.Dish' has no parameterless constructor.
Source=EntityFramework

So you need to correct your constructor. If you show your classes, it is possible to fix your error.

The second step to edit:

You should correct binding path in your DataTemplate of Text property:

<TextBlock Text="{Binding Path = Description}" FontWeight="Bold"/>

Cause there is no such property Dishes.Description in your Dish class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM