Introduction
This tip offers an easy way to automatically have INotifyPropertyChanged
implemented for every property in a given Entity Framework 6.0 entity class.
Background
In the "database first" option for using Entity Framework, Visual Studio generates your entity classes from an existing database. Purists might balk, but sometimes it would be nice if the generated classes implemented INotifyPropertyChanged
so you could data-bind directly to them in a WPF application. Unfortunately, Entity Framework 6.0 doesn't implement INPC for you.
Using the Code
First, install a NuGet package called PropertyChanged.Fody
. I'll assume you're already familiar with NuGet since it's probably how you added Entity Framework support to your project in the first place. When you install PropertyChanged.Fody
, NuGet will also install its dependency package called Fody
.
Suppose you have a generated entity class called Customer
that looks something like this:
public partial class Customer
{
}
We don't want to edit that class/file because it's generated. Instead, we'll leverage the fact that it's declared with the "partial
" keyword. This allows us to extend the Customer
class by placing the following code in a new file (or any file) in the same project.
using PropertyChanged;
[ImplementPropertyChanged]
public partial class Customer
{
}
That's it! Just follow the same pattern for any other entity classes that require INotifyPropertyChanged
. You can put all the partial classes in one file if you like.
So how does this work? PropertyChanged.Fody
is an "IL weaver". Installing the NuGet package injects a call to PropertyChanged.Fody
into the project's build process. It's essentially a post-build step that modifies the assembly after it's built. This particular weaver adds an implementation of INotifyPropertyChanged
to every class that has the [ImplementPropertyChanged]
attribute.
There are other attributes for customizing the behavior of PropertyChanged.Fody
but they apply to individual properties and can't be used on the properties in the generated files. However, you may want to use them in your own (regular non-generated) classes. See https://github.com/Fody/PropertyChanged for details.
In case you're wondering, the final assembly won't have a runtime dependency on PropertyChanged
despite the presence of the attribute, using clause, and project reference. Also, using PropertyChanged.Fody
(or any of the other Fody
plugins) won't break ClickOnce deployment.