回到目录
在项目开发过程中,出现了一个问题,就是新添加一个非空字段后,原来的程序逻辑需要被重新修改,即将原来的字段添加到程序里,这种作法是非常不提倡的,所以,我通过T4模版将原来的实体类小作修改,解决了这个问题,即,在实体里为非空属性添加默认值,事实上,也就那种几种,如string默认为string.Empty,int,short,long默认都是0,而datetime默认为当前日期,这些我们可以在T4模块中完成
看一下代码
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)#>();
<#
}
#>
}
保存模版后,看一下生成的类截图
作者:仓储大叔,张占岭,
荣誉:微软MVP
QQ:853066980
支付宝扫一扫,为大叔打赏!
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicEUK5CN0EzNfdUTJ91bvwFN4gzNzIzLclmcvx2Lc12bj91cn9Gbi52YvwVbvNmLzd2bsJmbj5ycldWYtl2Lc9CX6MHc0RHaiojIsJye.jpg)