Wednesday, October 13, 2010

WPF DataGrid Entity Framework 4.0

Tags: WPF, DataGrid, Entity Framework, Detached

When I populate the datagrid with linq + entity framework for example

myModel context = new myModel();
myDataGrid.ItemsSource = from a in context.Apples select a;

and then you create a new record via the DataGrid and you want to handle the event InitializingNewItem. You may want to check what the display order of apples is, you can not check via context as the record/s are detached so you have to look in items. The problem is that the new record is of type MS.Internal.NamedObject not Apple.

So you write the following LINQ query
var MaxDisplayOrder = (from Apple a in myDataGrid.Items select a.DisplayOrderNo).Max();

You run it and get the following error exception:
Unable to cast object of type 'MS.Internal.NamedObject' to type 'Apple'.

To solve this problem use OfType method
var MaxDisplayOrder = (from a in myDataGrid.Items.OfType<Apple>() select a.DisplayOrderNo).Max();

No comments:

Post a Comment