Adding INotifyPropertyChange in generated EF class

2019-07-07 00:48发布

问题:

So, my classes are auto-generated by EF:

//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Testje.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Ploeg
    {
        public Ploeg()
        {
        }

        public int Id { get; set; }
        public string Naam { get; set; }
        public string Icon { get; set; }
    }
}

When one of the properties change, I'd like to do a notifypropertychange. Is this possible somehow without editing this generated class?

回答1:

It would be possible, but I strongly suggest to not do this! Adding INotifyPropertyChanged in your model will lead to a bad separation of concerns.

Use events to highlight that the model has changed. Have a look here to see how this works: MSDN on standard event pattern

Or even better: MSDN cites Albahari Bros on the event pattern

In your viewmodel, implement INotifyProperty changed. Let your ViewModel than listen to the events from your model, adapt the data and push it to your view through INotifyPropertyChanged



回答2:

Yes you can, by using a NuGet package called PropertyChanged.Fody. Install the package and then create another partial class adding the [ImplementPropertyChanged] property like the one shown below;

using PropertyChanged;

[ImplementPropertyChanged]
public partial class Ploeg
{
}

That's it.

See GitHub for more information.



回答3:

In my case I added

INotifyPropertyChanged

as inheritance and seems to work like a charm. Using EF generated classes (Request_Comment is generated class EF)

Example:

namespace Requesto
{
    public partial class Request_Comment : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, e);
            }
        }
    }

}