如何在声明中有条件地设置基类

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))#>
}

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

1个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
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)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\Templates\Includes\EF.Utility.CS.ttinclude

位于<#= #>标签之间的部分只是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))#>

谢谢回复 - 没问题,但我想要的是默认行为。即,除非它是派生类,否则使所有类继承BaseItem。这行代码是T4的默认行为。 - MikeW
让我进一步澄清 - 这个默认的 BaseClass 不是模型的一部分 - 因为它看起来与由 T4 生成的类非常不同。因此,虽然可能不是最好的解决方案,但这是一个简单的解决方法。 - MikeW
@MikeW:因此,存在于<#= #>标记之间的T4模板部分是简单的C#表达式。你知道顶级类型的entity.BaseType评估结果是什么吗?例如,它是否为null - Merlyn Morgan-Graham

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,