将PropertyChanged.Fody添加到Entity Framework Model.tt

时间:2014-07-25 07:40:16

标签: entity-framework fody-propertychanged

我正在使用Entity Framework 6(Model First)。所以我有几个由model.tt为我生成的类。这是我的Car类:

//------------------------------------------------------------------------------
// <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; }
    }
}

我也在项目中的其他类上使用PropertyChanged.Fody。我有几个类,其属性只是从我生成的类中包装属性,如下所示:

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; }
        }
    }
}

所以,ProperyChanged.Fody会在我的Car属性上执行它的魔法而不是其他属性,但如果我要编辑我的Model.tt并添加[ImplementPropertyChanged]属性,我生成的类将全部通知财产变更。然后,我可以像这样修改CarWrapper中的Car属性:

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

如果我想通知Car内的房产变更,这会是一件好事吗?这会多余吗?还有其他建议吗?

1 个答案:

答案 0 :(得分:0)

我最终将[ImplementsPropertyChanged]添加到我的Car class的其他部分类中。这允许我控制实际需要实现属性更改的类。

虽然将其添加到.tt文件中似乎不会引起问题,但将其添加到另一半“#”;部分类允许更多控制。