Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObservableCollection better than ObjectSet

Why is it better (in WPF, C#, Entity Framework) to bind ListBox to an ObservableCollection created upon the ObjectSet (from Entity Framework) rather than binding to ObjectSet directly?

One more question: When I bind ListBox to ObservableCollection, any additions to the collection updates ListBox. Great. But ObservableCollection was created upon ObjectContext (in Entity Framework) and adding a new item to the collection doesn't add the item to the context... how to solve this????

like image 228
Cartesius00 Avatar asked May 31 '11 21:05

Cartesius00


2 Answers

(Note to your "One more question" point)

Entity Framework 4.1 offers a new feature which is especially useful in WPF applications - the local view of the object context. It is available through the Local property of DbSet<T>. Local returns an ObservableCollection<T> containing all entities of type T which are currently attached to the context (and not in state Deleted).

Local is useful because it stays automatically in sync with the object context. For example: You can run a query to load objects into the context ...

dbContext.Customers.Where(c => c.Country == "Alice's Wonderland").Load();

... and then expose the objects in the context as an ObservableCollection ...

ObservableCollection<Customer> items = dbContext.Customers.Local;

... and use this as the ItemsSource of some WPF ItemsControl. When you add or remove objects to/from this collection ...

items.Add(newCustomer);
items.Remove(oldCustomer);

... they get automatically added/removed to/from the EF context. Calling SaveChanges would insert/delete the objects into/from the database.

Likewise adding or removing objects to/from the context ...

dbContext.Customers.Add(newCustomer);
dbContext.Customers.Remove(oldCustomer);

... updates automatically the Local collection and fires therefore the notifications for the WPF binding engine to update the UI.

Here is an overview about Local in EF 4.1.

like image 166
Slauma Avatar answered Oct 01 '22 19:10

Slauma


ObservableCollection implements INotifyPropertyChanged as well as INotifyCollectionChanged, both of which WPF uses to rebind elements to the UI. Thus, you could add an item to the ObservableCollection and immediately the UI would update with no code interaction from you. ObjectSet implements neither, and so doesnt get this functionality.

like image 29
Tejs Avatar answered Oct 01 '22 18:10

Tejs