views:

272

answers:

1

I am getting started with Entity Framework using EF4 in VS 2010 RC. So far, I have done some simple console apps where I create an EDM, query it using LINQ to Entities, and output the results to the console.

Now I am building a demo WPF app to learn how to integrate EF4 with WPF. I use MVVM in my WPF apps, where each view (more or less) has a view model that includes data properties to which controls are bound. For example, my WPF demo app has a Customers property in the view model to which a dropdown in the view is bound. And as you may have guessed, my EDM contains a Customer entity.

Here is my question: How do I connect the LINQ to Entities results to my view model property? When I query against my Customer entity, it appears that I get an IQueryable<Customer> back. But my view model property is of type ObservableCollection<Customer>, which I need for the data bindings to work. So, how do I get from the IQueryable<Customer> to ObservableCollection<Customer>? Thanks for your help.

+1  A: 

According to MSDN, the ObservableCollection constructor can take a List<T> or IEnumerable<T>. Let's suppose queryable is your IQueryable<Customer>:

ObservableCollection<Customer> ocCustomer = new ObservableCollection<Customer>(queryable.ToList());
Dave Swersky
I'll check this out. It may be this simple, but with NHibernate, if I broke the collection, I lost dirty-checking.
David Veeneman
A more complete answer can be found here:http://stackoverflow.com/questions/2433591/does-wpf-break-an-entity-framework-objectcontext. Basically, the ObjectContext has to be updated when an object is added or removed from the observable collection by WPF. It's very simple to do with a collection class that derives from ObservableCollection<T>.
David Veeneman