Very simple LINQ and DataGrid, Data Binding Related Question

May 15, 2009 at 2:31 AM
Edited May 15, 2009 at 2:39 AM

Greetings,

First of all I'd like to apologize about my question since it's probably LINQ related and not DataGrid related directly but...

When I bind a LINQ query directly to the WPF DataGrid in a way that:

var query = from customer in dataContext.Customers orderby customer.Name select customer;
wpfDataGrid.ItemsSource = query;

 

then when I insert a new row or delete an existing row, LINQ to SQL DataContext -i.e. the dataContext object in the query above- can track the insert/update operation.
But when I bind the same query by getting a generic list out of it in a way that:

var query = from customer in dataContext.Customers orderby customer.Name select customer;
wpfDataGrid.ItemsSource = query.ToList();

then inserting a row to or deleting a row from the WPF DataGrid does not seem to notify the DataContext at hand and ChangeSet is empty.

Can anyone please explain the reason behind this? Since things seem to get interesting ,whether you bind a LINQ DataQuery or a generic List, DataContext can always track update changes, or so it seems.

Is it related to the INotifyPropertyChanging/INotifyPropertyChanged  interfaces implemented in the entity classes -e.g. Customer in the example above- or DataContext can keep track of changes for direct queries -i.e. DataQuery- and stops change tracking for converted/casted results such as generic lists. And if so, why can it still keep tracking changes on generic lists for updates but not for insert/delete operations?

Thanks in advance.

May 15, 2009 at 7:25 AM

This has come up before, and I believe the answer was that in the first case, you are binding to the query instance (which IIRC implements IEnumerable, or something to that effect at least), but in the second case, you are binding to the RESULTS of the query (converted to a List). That's a pretty big difference, and would explain the exact behavior you are seeing, since updates only modify existing items, but adding or deleting items modifies the collection itself (which in the second case only exists in wpfDataGrid.ItemsSource as you do nothing else with ToList()'s result).

If you need the results of the query as a List for some specific reason, you could always try assigning the result of query.ToList() to an intermediate, appropriately scoped variable, and then playing with that variable. That should get you your desired behavior.