Search code examples
entity-frameworkfody-propertychanged

Adding PropertyChanged.Fody to Entity Framework Model.tt


I am using Entity Framework 6 (Model First). So I have several classes that are generated for me by model.tt. Here is my Car class:

//------------------------------------------------------------------------------
// <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 MyNamespace
{

    using System;
    using System.Collections.Generic;

    public partial class Car
    {
        public Car()
        {
            this.Wheels = new HashSet<Wheel>();
        }

        public int CarId { get; set; }
        public string Make { get; set; }
        public string Model { get; set; }
        public string Year { get; set; }
        public string VIN { get; set; }

        public virtual ICollection<Wheel> Wheels { get; set; }
    }
}

I also use PropertyChanged.Fody on other classes in my project. I have several classes with properties that are simply wrapping properties from my generated classes, like so:

using System;
using PropertyChanged;

namespace MyNamespace
{
    [ImplementPropertyChanged]
    public class CarWrapper
    {

        public CarWrapper(Car car)
        {
            Car = car;
        }

        public Car car { get; set; }

        public string Make
        {
            get { return Car.Make; }
            set { Car.Make = value; }
        }

        public string Model
        {
            get { return Car.Model; }
            set { Car.Model = value; }
        }       

        public string Year
        {
            get { return Car.Year; }
            set { Car.Year = value; }
        }

        public string VIN
        {
            get { return Car.VIN; }
            set { Car.VIN = value; }
        }
    }
}

So, ProperyChanged.Fody would do it's magic on my Car property and not the others, but if I were to edit my Model.tt and add the [ImplementPropertyChanged] attribute, my generated classes would all notify on property change. I could then modify Car property in CarWrapper like so:

[AlsoNotifyFor("Make")]
[AlsoNotifyFor("Model")]
[AlsoNotifyFor("Year")]
[AlsoNotifyFor("VIN")]
public Car car { get; set; }

Would this be a good thing to do at all if I want to be notified of property changes within Car? Would it be redundant? Any other suggestions?


Solution

  • I ended up adding [ImplementsPropertyChanged] to my Car class's other partial class. This allows me to control which classes actually need to implement property changes.

    Although adding it to the .tt file does not appear to cause issues, adding it to the other 'half' of the partial class allows for more control.