MVC.net + subsonic Auto Generate MetaData Classes from TT

六月ゝ 毕业季﹏ 提交于 2019-12-21 05:58:23

问题


Not a question but i dont have a blog and i have just created a new subsonic TT file that will generate the Metadata classes automatically for the subsonic classes so you can skip out some work when using dataAnnotation and CreateForModel etc

so the first step is to amend your ActiveRecord.TT with the following

using System.ComponentModel; 
using System.Data.Common; 
using System.ComponentModel.DataAnnotations;

Then above the generation of the class name we need to make a reference to our metadata like so:

[MetadataType(typeof(<#=tbl.ClassName#>MetaData))]
public partial class <#=tbl.ClassName#>: IActiveRecord

thats everything completed for ActiveRecord.tt

now your MetaGenerator TT is below, notice that my include is for MySql you will need to amend this line to account for your DB type

<#@ include file="MySQL.ttinclude" #>  
using System;  
using System.ComponentModel;  
using System.ComponentModel.DataAnnotations;  

namespace <#=Namespace #>  
{  
<#  
var tables = LoadTables();  
foreach(Table tbl in tables)  
{  
if(!ExcludeTables.Contains(tbl.Name))  
{  
#>  
public class <#=tbl.ClassName#>MetaData  
{  
<# foreach(Column col in tbl.Columns)  
{  
if (tbl.ClassName == col.CleanName)  
{  
col.CleanName += "X";  
} #>    
[DisplayName("<#=col.CleanName #>: ")]   
<# if(String.IsNullOrEmpty(CheckNullable(col))) { #>  
[Required(ErrorMessage = "<#=col.CleanName #> is a required element.")] <# }      
#>          
public <#=col.SysType #><#=CheckNullable(col)#> <#=col.CleanName #>  { get;set; }  
<#    
}   
#>  
}  
<# }  
} #>   
}  

I have added a small check to see if the item is nullable or not, if not then i am adding a required element.

now this is not brilliant, but it would say quite a bit of work for a large database and using editorFor etc is a brilliant way to knock out pages without even thinking about it.

when creating a strongly type view for a create or edit i make reference to the MetaData class rather than to the subsonic class and everything is then plane sailing

add this to your own custom edited CodeTemplates and you dont really have to do much on the Html side of things once you have a master page created.

anyway enjoy im sure that it would be useful for one person!


回答1:


have done a better version of this onto the docs here Subsonic TT Extension for Subsonic Buddy Classes



来源:https://stackoverflow.com/questions/2321614/mvc-net-subsonic-auto-generate-metadata-classes-from-tt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!