EF架構~在T4模版中為所有(you)屬性加(jia)默認值(zhi)
在(zai)項目(mu)開發過程(cheng)中,出現了一(yi)個(ge)(ge)問題,就是(shi)新(xin)(xin)添(tian)加(jia)一(yi)個(ge)(ge)非空(kong)字段(duan)后,原來的(de)程(cheng)序邏輯(ji)需要被(bei)重新(xin)(xin)修改(gai),即(ji)將(jiang)原來的(de)字段(duan)添(tian)加(jia)到(dao)程(cheng)序里,這種作法是(shi)非常不提倡的(de),所以(yi),我(wo)通(tong)過T4模(mo)(mo)版(ban)將(jiang)原來的(de)實體類小(xiao)作修改(gai),解決了這個(ge)(ge)問題,即(ji),在(zai)實體里為(wei)非空(kong)屬(shu)性添(tian)加(jia)默(mo)認值,事實上,也(ye)就那種幾種,如string默(mo)認為(wei)string.Empty,int,short,long默(mo)認都是(shi)0,而(er)datetime默(mo)認為(wei)當前日期,這些(xie)我(wo)們可以(yi)在(zai)T4模(mo)(mo)塊中完成
看一下代碼
public <#=code.Escape(entity)#>() { <# foreach (var edmProperty in propertiesWithDefaultValues) { #> this.<#=code.Escape(edmProperty)#> = <#=typeMapper.CreateLiteral(edmProperty.DefaultValue)#>; <# } foreach (var navigationProperty in collectionNavigationProperties) { #> this.<#=code.Escape(navigationProperty)#> = new HashSet<<#=typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType())#>>(); <# } foreach (var complexProperty in complexProperties) { #> this.<#=code.Escape(complexProperty)#> = new <#=typeMapper.GetTypeName(complexProperty.TypeUsage)#>(); <# } #> }