T4模版为我们在ORM操作上提供了便捷,它很方便的可以对实体进行全局性的修改,之前我介绍过通过T4来为属性加默认性,而今天我主要告诉大家如何使用T4模版将getter,setter块改为自己需要的,何为自己需要的?这当然是符合你当前项目规则的,如,我希望监听每个属性的修改过程,这正如之前linq to sql的实体类一样,它用来监听你属性的修改前与修改后,在两个时机都可以分别订阅你自己的事件,多么灵活,呵呵。
来看一下,我项目中实体类最后的效果图
下面是T4模块的属性获取的私有方法代码,源于EF5中的T4模版
public string Property(EdmProperty edmProperty) { return string.Format( CultureInfo.InvariantCulture, " {6} {1} {5}; {0} {1} {2} {{ {3}get {{ return {5}; }} {4}set {{ if ({5}!=value) {{ OnPropertyChanging("{2}", {5}) ; {5}=value; OnPropertyChanged("{2}", {5}); }}}} }} ", Accessibility.ForProperty(edmProperty), _typeMapper.GetTypeName(edmProperty.TypeUsage), _code.Escape(edmProperty), _code.SpaceAfter(Accessibility.ForGetter(edmProperty)), _code.SpaceAfter(Accessibility.ForSetter(edmProperty)), "_"+_code.Escape(edmProperty).ToLower(), "private" ); }
而最后生成它代码如下
[Serializable] public partial class WebManageRole_WebManageMenus : Frameworks.Entity.Core.EntityBase { private int _webmanagemenus_menuid; public int WebManageMenus_MenuID { get { return _webmanagemenus_menuid; } set { if (_webmanagemenus_menuid != value) { OnPropertyChanging("WebManageMenus_MenuID", _webmanagemenus_menuid); _webmanagemenus_menuid = value; OnPropertyChanged("WebManageMenus_MenuID", _webmanagemenus_menuid); } } } private int _webmanageroles_manageroleid; public int WebManageRoles_ManageRoleID { get { return _webmanageroles_manageroleid; } set { if (_webmanageroles_manageroleid != value) { OnPropertyChanging("WebManageRoles_ManageRoleID", _webmanageroles_manageroleid); _webmanageroles_manageroleid = value; OnPropertyChanged("WebManageRoles_ManageRoleID", _webmanageroles_manageroleid); } } } }
事实上,代码我们并不是很满意,因为它不够漂亮,呵呵,我们更喜欢换行之后的代码,当然你可以在T4里加一个 这种换行标记来实现。
经过我的测试,还是将它换一下行吧,呵呵,格式化一下看着顺眼点,代码如下
public string Property(EdmProperty edmProperty) { string strReg=string.Empty; return string.Format(CultureInfo.InvariantCulture, @" {7}{6} {1} {5}; {7}{0} {1} {2} {{{3} {8}get {8}{{ {9}return {5}; {8}}}{4} {8}set {8}{{ {9}if ({5}!=value) {9}{{ {10}OnPropertyChanging(""{2}"", {5}) ; {10}{5}=value; {10}OnPropertyChanged(""{2}"", {5}); {9}}} {8}}} {7}}} ", Accessibility.ForProperty(edmProperty), _typeMapper.GetTypeName(edmProperty.TypeUsage), _code.Escape(edmProperty), _code.SpaceAfter(Accessibility.ForGetter(edmProperty)), _code.SpaceAfter(Accessibility.ForSetter(edmProperty)), "_"+_code.Escape(edmProperty).ToLower(), "private", strReg.PadRight(0), strReg.PadRight(4), strReg.PadRight(8), strReg.PadRight(12)); }
希望代码可以给你带来快乐!