2011-09-20 5 views
4

내 edmx에서 클래스를 빌드하고 파생 클래스를 제외하고 원활하게 작동하는 수정 된 T4 템플릿이 있습니다.조건부로 선언에서 기본 클래스를 설정하는 방법

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

TranslatedProduct : Product : BaseItem // dang 

은 내가 조건부 무시하도록 T4 템플릿을 설정할 수있는 방법과에 대한 혼란 스러워요 : - :

<#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#>partial class <#=code.Escape(entity)#><#=code.StringBefore(" : ", code.Escape(entity.BaseType))#> : BaseItem 
BASEITEM를 파생 클래스의 경우 즉, 예를 들어

TranslatedProduct : Product 

내 머리 속에 나는 그것을 상상했다. -

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을 제공 한 스크립트는 항상 나타납니다. 이것은 부러진 것 같습니다.

원래의 코드는 다음과 같습니다

C :

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

이것은에 정의 된 클래스를 사용하여 \ 프로그램 파일 마이크로 소프트 비주얼 스튜디오 10.0 \ Common7 \ IDE \ 확장 \ 마이크로 소프트 \ (86) \ 엔티티 프레임 워크 도구 템플릿 \가

<#= #> 태그 사이에 스크립트의 일부 단지 C#을 표현하고, 일을 \ EF.Utility.CS.ttinclude 포함 \ 이러한 표현식에 의해 반환 된 문자열은 인라인으로 삽입됩니다.

code.Escape 메서드는 형식 이름 (문자열) 또는 빈 문자열을 반환합니다.

code.StringBefore은 두 번째 문자열 (기본 유형 이름) 앞에 두 번째 문자열이 null 또는 비어 있지 않은 경우에만 첫 번째 문자열 (" : ")을 추가합니다.

달성하려는 작업을 수행하려면 사용하는 것과 동일한 트릭을 사용할 수 있지만 그 반대입니다. 불행히도 어떤 종류의 AppendIfNotDefined 메소드가 없으므로 기존 클래스를 사용할 수 없습니다. 그래서 우리는 좀 더 복잡한 표현을 사용할 것입니다.

대신에 :

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

여기에 전체 라인의 모두 함께 벼락치기 :

code.StringBefore(" : ", 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'이 최상위 유형에 대해 평가하는 것을 알고 있습니까? 예 : 'null'입니까? –

관련 문제