Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

c# - 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????

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

(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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...