2011-09-20 23 views
4

我有一個修改後的T4模板,它可以從我的edmx構建類,除了派生類外,它的工作流暢。如何在聲明中有條件地設置基類

Product : BaseItem // works fine as do all top level classes 

TranslatedProduct : Product : BaseItem // dang 

我很困惑如何以及在哪裏可以有條件地設置T4模板忽視:BaseItem在派生類中的情況下 - 即

TranslatedProduct : Product 

例如:

<#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#>partial class <#=code.Escape(entity)#><#=code.StringBefore(" : ", code.Escape(entity.BaseType))#> : BaseItem 

在我的腦海中,我想像它 -

if(code.Escape(entity.BaseType).Equals(string.empty) 
{ 
    <#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#>partial class <#=code.Escape(entity)#> : BaseItem 
} 
else 
{ 
<#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#>partial  class <#=code.Escape(entity)#><#=code.StringBefore(" : ", code.Escape(entity.BaseType))#> 
} 

但我收到語法錯誤,所以我想看看是否有其他人試過這個,如果我在正確的道路上

回答

11

您提供硬編碼: BaseItem始終顯示的腳本。這似乎打破了。

原始代碼是:

<#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#>partial class <#=code.Escape(entity)#><#=code.StringBefore(" : ", code.Escape(entity.BaseType))#> 

這將使用定義的類:

C:\ Program Files文件(x86)的\微軟的Visual Studio 10.0 \ Common7 \ IDE \擴展\微軟\實體框架工具\模板\包括\ EF.Utility.CS.ttinclude

<#= #>標籤之間的腳本的部分僅僅是C#表達式和日由這些表達式返回的字符串被內聯插入。

code.Escape方法將返回類型名稱(作爲字符串)或空字符串。

code.StringBefore將在第二個字符串(基本類型名稱)之前追加第一個字符串(" : "),但僅當第二個字符串不爲空或空時追加。

要做你想要完成的事情,你可以使用他們使用的相同技巧,但相反。不幸的是,你不能使用他們現有的課程,因爲他們沒有某種AppendIfNotDefined方法。所以我們只會使用更復雜的表達式。

相反的:

code.StringBefore(" : ", code.Escape(entity.BaseType)) 

我們會寫:

code.StringBefore(" : ", 
    string.IsNullOrEmpty(code.Escape(entity.BaseType)) 
     ? "BaseItem" 
     : code.Escape(entity.BaseType) 
    ) 

這裏是整條生產線,全部擠在一起:

<#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#>partial class <#=code.Escape(entity)#><#=code.StringBefore(" : ", string.IsNullOrEmpty(code.Escape(entity.BaseType)) ? "BaseItem" : code.Escape(entity.BaseType))#> 
+0

感謝您的答覆 - 這很好,但什麼我以後是默認行爲。即。使所有類繼承BaseItem,除非它是派生類。這行代碼是T4的默認行爲。 – MikeW

+0

讓我進一步澄清 - 這個默認的BaseClass不是模型的一部分 - 因爲它看起來與T4生成的類非常不同。因此,雖然可能不是最好的解決方案,但它是一個簡單的解決方法 – MikeW

+0

@MikeW:因此,位於'<#= #>'標記之間的T4模板部件是簡單的C#表達式。你知道什麼'entity.BaseType'評估爲頂級類型?例如,它是否爲空? –