问题描述:

until now i was working with Visual Studio 2010 and Entity Framework 4.x. (Database First). For some of my generated Entity Classes i added a partial Class definition and some readonly properties. To get notified on property changes, i could handle the PropertyChanged event of the Entity and raise a PropertyChanged event for the added readonly property if one of the queried properties has changed. Easy as pie.

Recently i switched to Visual Studio 2012, which contains Entity Framework 5 by default.

I created a new model from an existing database (Database First) and the Entity Classes are generated. But it seems, that the generated classes have not the ability to utilize INotifyPropertyChanged - because they are POCO classes (which is the default code generation strategy) and hence do not derive from EntityObject as in Entity Framework 4.x..

So my first question is: with Entity Framework 5 (Database First), how can i get notified on property changes? This somehow must be possible, because Databinding in WPF does work, even if one binds a just created instance of an entity class (so that it is not a dynamic entity proxy from a context query)..

My second question is: with Entity Framework 5 (Database First), how can i bind an associated collection of an entity object to a wpf control? The generated Association Property of an entity relation is ICollection with a default instance of HashSet. So when a related entity object is added or removed, the bound wpf control does not get notified on that collection change (even when using the ObservableCollection in the Local Property of an Entity Set, the association properties are still HashSets without change notification..).

What is the "intended" way to achieve these essential things?

thanks in advance,

Hannes

网友答案:

Manual approach: why don't you use code first and raise PropertyChanged event manually from interesting setters? A lot of work but a lot of control.

Dynamic approach Let's say you have an EditViewModel that has a property named Document witch contains a reference to a generated EF entity and you need to bind to this Document properties.

Leveraging the adapter design pattern, you can wrap the entity in a class witch implements INotifyPropertyChanged and raises PropertyChanged event when ever a setter is called. Instead of binding to the entity you bind on the interceptor witch raises property changed and delegates property calls to the wrapped entity object using the reflection api.

You can find here a good exemple in witch the goal is to make the ViewModel implement INotifyPropertyChanged but you can do this for the document as well: http://www.hightech.ir/SeeSharp/best-implementation-of-inotifypropertychange-ever

相关阅读:
Top