0

Entity Framework Local property is an ObservableCollection and can be bind to lets say a datagrid. But its items do not update with call to LoadAsync, or do update actually but do not reflect into datagrid. Consider following example:

XAML

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition />
    </Grid.RowDefinitions>
    <StackPanel Orientation="Horizontal">
        <Button Content="Load" Click="btnLoad_Click"/>
        <Button Content="LoadAsync" Click="btnLoadAsync_Click"/>
        <Button Content="SetDataSource" Click="btnSetDataSource_Click"/>
    </StackPanel>
    <DataGrid Name="grdTest" Grid.Row="1"/>
</Grid>

Code Behind

TestContext db = new TestContext();
public MainWindow()
{
    InitializeComponent();
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
   grdTest.ItemsSource = db.Suppliers.Local;
}

private void btnLoad_Click(object sender, RoutedEventArgs e)
{
    var beforQuery = db.Suppliers.Local;
    db.Suppliers.Load();
}

private void btnLoadAsync_Click(object sender, RoutedEventArgs e)
{
    var beforQuery = db.Suppliers.Local;
    db.Suppliers.LoadAsync();
}

private void btnSetDataSource_Click(object sender, RoutedEventArgs e)
{
    grdTest.ItemsSource = null;
    grdTest.ItemsSource = db.Suppliers.Local;
}
  1. If I press Load button first, it behave as expected (load all items into collection and they are reflected into datagrid)

  2. If I press LoadAsync button first, Only one item is loaded to Local items (which is another question, why only one item), but it is not reflected into datagrid, I can press SetDataSource to see that.

  3. Each time I press LoadAsync only one item is added to the previous set!!

  4. And If I press LoadAsync and then Load an error would come up and say "An ItemsControl is inconsistent with its items source"

Now my question is, how can I use LoadAsync and Local items properly? If I can not load items form database with LoadAsync method, then what is its use?

mesmoll
  • 167
  • 2
  • 7

1 Answers1

1

The problem is that the ItemsSource is being updated on a different thread than the control's thread. If you're using .NET 4.5, you can use EnableCollectionSynchronization to allow multiple threads to access a collection.

See this answer for an example.

Community
  • 1
  • 1
jjj
  • 4,822
  • 1
  • 16
  • 39