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模板和解決上面的兩個問題,請留言,與大家一起分享