将列表框绑定到数据库表

本文关键字:数据库 绑定 列表 | 更新日期: 2023-09-27 18:24:52

我正在构建一个WPF应用程序。我已经使用实体框架代码优先创建了数据库,现在我想将我的数据库与GUI一起使用。我在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;
}

我得到了一个例外:

EntityFramework.SqlServer.dll 中发生类型为"System.Reflection.TargetInvocationException"的未处理异常

附加信息:由呼叫目的地生成的异常(已翻译)。

更新:

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: 

答案

在分析完整异常时,类构造函数似乎不能有参数。

将列表框绑定到数据库表

首先:

内部异常显示您的错误:

Message=类"Cw2.Dish"没有无参数构造函数
来源=EntityFramework

所以你需要修正你的构造函数。如果您显示您的类,则可以修复您的错误。

编辑的第二步:

您应该更正Text属性的DataTemplate中的绑定路径:

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

因为在Dish类中没有这样的属性Dishes.Description