访问T4模板中的自定义属性(VS2012 MVC4)
我正在尝试访问我的自定义属性,如我正在编写的T4控制器模板中附加到我的模型属性的SortableAttribute
。 我已经将List.tt中的类块,程序集和导入复制为样板文件。
首先,我尝试按如下方式转换属性:
然而,这并没有产生积极的结果,因为我的项目命名空间对T4来说是未知的。 为了解决这个问题,我添加了项目的dll并导入了所需的命名空间。
它起初似乎很成功(例如,命名空间导入没有错误),但它仍然没有找到我的属性。 如果我用MyProject.Filters.SortableAttribute
替换SortableAttribute
,则错误消息是在MyProject.Filters
找不到SortableAttribute
。
为了解决这个问题,我改变了我的代码如下:
我以为我已经中了大奖,但我很快就意识到这个property.GetCustomAttributes(true)
返回所有属性但不是我的……
示例模型:
public class MyModel { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] [Display(Name = "Full Name")] [Sortable] public int Name { get; set; } }
SortableAttribute
实现:
using System; namespace MyProject.Filters { [AttributeUsage(AttributeTargets.Property)] public class SortableAttribute : Attribute { public SortableAttribute(string by = "") { this.By = by; } public string By { get; private set; } } }
你能指点我正确的方向吗?
任何帮助是极大的赞赏!
编辑:
事实certificate, property.GetCustomAttributes(true)
确实返回了我的属性,但SortableBy中的以下表达式总是求值为null
:
(string) attribute.GetType().GetProperty("By").GetValue(attribute, null);
知道为什么会这样吗?
记住:Build修复了很多问题,但REBUILD可以解决所有问题!
回顾一下并帮助其他人编写T4模板,这里有一些可以用作样板的工作代码:
读取.tt文件中的自定义属性(基于任何默认视图模板中的Scaffold()):
<#+ string SortableBy(PropertyInfo property) { foreach (object attribute in property.GetCustomAttributes(true)) { var sortable = attribute as SortableAttribute; if (sortable != null) return sortable.By == "" ? property.Name : sortable.By; } return property.Name; } #>
模型:
public class MyModel { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] [Display(Name = "Full Name")] [Sortable] public int Name { get; set; } }
SortableAttribute
实现:
using System; namespace MyProject.Filters { [AttributeUsage(AttributeTargets.Property)] public class SortableAttribute : Attribute { public SortableAttribute(string by = "") { this.By = by; } public string By { get; private set; } } }
对于任何想要如何使用MVC5执行此操作的人: https ://johniekarr.wordpress.com/2015/05/16/mvc-5-t4-templates-and-view-model-property-attributes/