【问题标题】:How to conditionally set base class in declaration如何在声明中有条件地设置基类
【发布时间】:2011-09-20 23:59:08
【问题描述】:

我有一个修改过的 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))#>
}

但我收到语法错误,所以我想看看是否有其他人尝试过,以及我是否走在正确的道路上

【问题讨论】:

    标签: c# .net entity-framework t4


    【解决方案1】:

    您提供的脚本硬编码: BaseItem 始终出现。这似乎坏了。

    原代码为:

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

    这使用了一个定义在:

    C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\Templates\Includes\EF.Utility.CS.ttinclude

    &lt;#= #&gt; 标记之间的脚本部分只是 C# 表达式,这些表达式返回的字符串是内联插入的。

    code.Escape 方法将返回类型名称(作为字符串)或空字符串。

    code.StringBefore 将在第二个字符串(基本类型名称)之前附加第一个字符串 (" : "),但前提是第二个字符串不为 null 或空。

    要完成您想要完成的事情,您可以使用他们使用的相同技巧,但反过来。不幸的是,你不能使用他们现有的类,因为他们没有某种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))#>
    

    【讨论】:

    • 感谢您的回复 - 很好,但我追求的是默认行为。 IE。使所有类都继承 BaseItem,除非它是派生类。这行代码是T4的默认行为。
    • 让我进一步澄清 - 这个默认 BaseClass 不是模型的一部分 - 因为它看起来与 T4 生成的类非常不同。因此,虽然可能不是最好的解决方案,但它是一种简单的解决方法
    • @MikeW:所以,&lt;#= #&gt; 标签之间存在的 T4 模板部分是简单的 C# 表达式。你知道entity.BaseType 对顶级类型的评价是什么吗?例如,是null
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 2019-04-09
    • 2019-07-06
    相关资源
    最近更新 更多