Implement INotifyPropertyChanged on generated Entity Framework classes

前端 未结 5 1050
有刺的猬
有刺的猬 2020-11-30 11:11

I have an SQL DB and am implementing a WPF UI to update it. If I use EF5 to generate the classes from the DB, how can I implement INotifyPropertyChanged on the generated cla

相关标签:
5条回答
  • 2020-11-30 11:42

    You can edit the EF template (.tt file) to generate the propertyChanged stuff on your properties, or (a bit risky:)) to edit the generated classes. The last is a bit risky, because if you regenerate the model, all changes will be lost. So maybe the variant with the wrapper classes or the template editing (a bit hard :S) are the best.

    0 讨论(0)
  • 2020-11-30 11:45

    There's a NuGet package called PropertyChanged.Fody that makes adding INotifyPropertyChanged to a classes properties really simple. Once you've installed the package just add the [ImplementPropertyChanged] attribute to any class or partial class and the package will add INotifyPropertyChanged for you.

    Here's a simple example of it's use;

    using PropertyChanged;
    
    [ImplementPropertyChanged]
    public partial class Order
    {
    }
    

    See GitHub for more information.

    0 讨论(0)
  • 2020-11-30 11:47

    Make all your EF generated classes inherit from a class which implements the INotifyPropertyChanged interface (using the non-generated partial classes you probably already defined). Add a method to this base class, which raises the PropertyChanged event with an empty string as PropertyName. Then, every time you call this method on an EF generated class instance, all its modified properties will be refreshed in your WPF UI.

    0 讨论(0)
  • 2020-11-30 12:03

    If you follow the recommended MVVM pattern for WPF, you can treat your generated classes as the Model, and then write ViewModel wrappers that implement INotifyPropertyChanged. The ViewModel classes would access your DB classes and expose properties that you can bind to your UI in XAML.

    As noted in your comment, this can result in a lot of work writing boilerplate code, but there are some ways to deal with that. See this question for some ideas.

    While more work at first, the MVVM pattern can definitely pay off in the long run if you ever need to do any intermediate formatting or processing, or if you need to change your database classes without affecting the UI.

    0 讨论(0)
  • 2020-11-30 12:04

    I needed to do the same recently but with Winforms. If you don't want to follow the MVVM pattern as suggested by bde you can modify the t4 template to implement INotifyPropertyChanged on your generated entities.

    This answer helped me: https://stackoverflow.com/a/12192358/1914530

    0 讨论(0)
提交回复
热议问题