ObservableCollection better than ObjectSet
Why is it better (in WPF, C#, Entity Framework) to bind ListBox
to an Observab开发者_如何学JAVAleCollection
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????
(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.
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.
精彩评论