A first chance exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll

entity-framework exception invalidoperationexception wpf



I'm using DataBase First Entity Framework v4.4. In the DB (and data model) is Table1 that has a 1:many relationship to Table2.

I am binding a DataGrid in WPF to Table1.Local.First().Table2 (for simplicity, assume that there is an entity in Table1.Local to begin with).


Public SomeEntityDBContextWithTable1AndTable2 Container { get; set; }
Public ICollection Table2ToDisplay { get { return Container.Table1.Local.First().Table2; } } //Note: :Many navigation properties return ICollection<T>, but the object type is of ObservableCollection<T>.

In XAML, I have the following

<GroupBox Header=Table2 DataContext="{Binding Path=Table2ToDisplay, UpdateSourceTrigger=PropertyChanged}">
    <DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False" CanUserAddRows="True">
            <!--A bunch of columns-->

When clicking inside a NewItemPlaceHolder that happens to be a text box, I get the System.InvalidOperationException occuring in PresentationFramework.dll. This doesn't crash my application, but I see it in the Output. My guess is that entities are added on another thread, and thus CollectionChanged event fires on another thread, and this causes the InvalidOperationException. However, since the code is mainly done via XML, I can't seem to find a way to handle this exception (or is it already being handled, it's just that it is being reported to Output). Is there a safe way to use CanUserAddRows="True" with EntityFramework where ":Many" navigation properties are of type ObservableCollection?

I should point out that I have also tried wrapping my Table2ToDisplay property inside a CollectionViewSource, but I still see the InvalidOperationException in the output.

Thanks in advance.

3/14/2013 4:14:44 PM

Accepted Answer

Okay. Changing Visual Studio's debugger to stop at all exceptions lead me to some insite. The exception was "NewItemPlaceHolder is not allowed during an AddNew...", which occured because of a PropertyChanged event on my Entity. Turns out this exception was already being handled, so I think I'm good.

3/14/2013 4:48:08 PM

Popular Answer

I'm going to take a wild guess since not all the details are present (update code, stack trace, etc) that you are changing the bound collection in a non-ui thread.

In which case, you need:

(in update logic)

Application.Current.Dispatcher.Invoke((Action)(() =>
       // update collection here

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow