Entity Framework 5 自定义代码生成模板 及 两个小Bug(可能是)

     Entity Framework 5 发布有一定时间了,但学习资源确实不多,更何况英语差的我,看英语确实费力,不管怎么样,问题还是解决了,查看很多人写的文章(让我看的想放弃,更想找到答案),都没有到到关于自定义代码生成的模板的文章,最后打开VS2010 创建了一个model.tt文件,最终在它里面找到了相应的方法,现给大家分享一下。(最近也写过两篇关于EF5的文章

  在自定义过程中,发现有几处问题,可能是Bug,也可能是故意这样设计的,但这两位问题对个人来说,还是有一定的影响,总觉得不太完美,希望这几位在后续的版本当中会得到改善,下面会列出这几个问题。

第一步:介绍一下Model的目录结构,与以前的版本变化还是比较大的

第二步:打开代码生成文件Model.tt,从网上了解到.tt文件是权限T4写的,本人不了解T4,不知是否真假,应该不会错的,呵呵,如果对T4了解的人,看起来应该会很简单。

打开.tt文件,找到如下代码,这是生成类属性的主要代码

var simpleProperties = typeMapper.GetSimpleProperties(entity);
    if (simpleProperties.Any())
    {
        foreach (var edmProperty in simpleProperties)
        {
#>
    <#=codeStringGenerator.Property(edmProperty)#>
<#
        }
    }

生成如下代码

修改后的代码,主要代码就是edmProperty.Documentation != null && edmProperty.Documentation.Summary != null

    var simpleProperties = typeMapper.GetSimpleProperties(entity);
    if (simpleProperties.Any())
    {
        foreach (var edmProperty in simpleProperties)
        {
#>
<#  if (edmProperty.Documentation != null && edmProperty.Documentation.Summary != null)
    { 
#>
    /// <summary><#= edmProperty.Documentation.Summary #></summary>
    <#=codeStringGenerator.Property(edmProperty)#>
<#  }#>
<#  if (edmProperty.Documentation == null)
    { 
#>
    <#=codeStringGenerator.Property(edmProperty)#>
<#  }#>
<#
        }
    }

生成后的类属性,加上了注释

类属性定义可以,哪么 DbSet 和Class 是否也可以加上注视呢,结果测试发现了问题,这里可能是Bug,因为每次得到的Documentation 总是Null

打开 Model.Content.tt文件

修改如何代码为 但这里的 entitySet.Documentation 总是 Null ,可能是Bug吧

 foreach (var entitySet in container.BaseEntitySets.OfType<EntitySet>())
    {
#>
<#  if (entitySet.Documentation != null && entitySet.Documentation.Summary != null)
    { 
#>
    /// <summary><#= entitySet.Documentation.Summary #></summary>
    <#=codeStringGenerator.DbSet(entitySet)#>
<#  }#>

<#  if (entitySet.Documentation == null)
    { 
#>
    /// <summary><#= entitySet #></summary>
    <#=codeStringGenerator.DbSet(entitySet)#>
<#  }#>
<#
    }

第二个可能的小Bug是在复制实体时,其的属性都可以复制,但是文档属性不能复制过来

另外,以上都是类文件的定义,生成的Sql语句没有注释,但也没找到相应生成Sql的模板,如果可以定义Sql模板,就可以把生成的Sql代上注释,这样就完美了,如果哪位兄弟知道如何定义Sql模板和解决上面的两个问题,请留言,与大家一起分享

原文地址:https://www.cnblogs.com/Fengger/p/2698101.html