我将实体绑定到 CollectionViewSource。然后我在后面的代码中查询。因为 id 字段是 PK 所以我认为我应该使用 FirstOrDefault() 让我的应用程序执行得更快。但它总是抛出一个异常......
XAML:
<Window.Resources>
<CollectionViewSource x:Key="contractlogoesViewSource" d:DesignSource="{d:DesignInstance my:contractlogo, CreateList=True}" />
</Window.Resources>
<Grid>
<Grid DataContext="{StaticResource contractlogoesViewSource}" HorizontalAlignment="Left" Margin="12,12,0,0" Name="grid1" VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
...
后面的代码:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
VBDAdvertisement.vbdadvertisementEntities vbdadvertisementEntities = new VBDAdvertisement.vbdadvertisementEntities();
System.Windows.Data.CollectionViewSource contractlogoesViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("contractlogoesViewSource")));
contractlogoesViewSource.Source = vbdadvertisementEntities.contractlogoes.Where(q => q.id.Equals(3)).FirstOrDefault();
}
它抛出一个未处理的异常:
An unhandled exception of type 'System.ArgumentException' occurred in
PresentationFramework.dll
Additional information: 'VBDAdvertisement.customer' is not a valid value for
property 'Source'.
但是当我从表达式树中省略 FirstOrDefault() 时,如下所示:
contractlogoesViewSource.Source = vbdadvertisementEntities.contractlogoes.Where(q => q.id.Equals(3));
它运作良好!
那么为什么 FirstOrDefault() 会导致错误呢?
在这种情况下,我应该使用 FirstOrDefault(),如果我使用 FirstOrDefault(),我的应用程序会执行得更快吗?
ps:我正在设计一个编辑表单,所以我只想加载一个项目。