2011-12-01 1 views
4

데이터베이스의 속성은 모두 작은 경우이며 단어 분리에 밑줄을 사용합니다. 예컨대 :Entity Framework POCO 엔터티 템플릿 : 형식 속성 이름

customer_order_id 

내 PropertyNameCodingConvention을 준수하기 위해 속성 이름을 원하는, 즉 : customer_order_id -> CustomerOrderId 나는 그것을 달성하기 위해 T4 템플릿을 변경했지만 이미 사용할 수있는 솔루션이 있다면 제가 궁금

.

+0

궁금한 점이 있으시면이 규칙을 준수하기 위해 맞춤식 규칙을 살펴 보셨습니까? http://blogs.msdn.com/b/adonet/archive/2011/01/10/ef-feature-ctp5-pluggable-conventions.aspx –

+0

예, 제 이해는 CodeFirst 접근 방식에 적용됩니다. 나는 데이터베이스를 가지고 C# 코드를 생성 할 필요가있다. (그래서 '코드 마지막'접근법이다.) –

답변

0

이 템플릿에 변화를 필요로하지만, 여기에 내가 그것을 어떻게 있습니다 :

  1. (오른쪽 마지막 닫는 전에 '#>'태그) EntityPoco.tt의 끝에 추가

    private string N(string input) { 
        return System.Text.RegularExpressions.Regex.Replace(input, 
         "(?:_|^)([a-z])", 
         match => match.Groups[1].Value.ToUpper()).Replace("_", ""); 
    } 
    
  2. 속성 이름이 출력되는 모든 위치를 줄 바꿈하십시오 (총 6 개, 아래 코드 참조). 여기

은 전체 텍스트입니다 : EDMX 파일에서

<# 
//********************************************************* 
// 
// Copyright (c) Microsoft. All rights reserved. 
// This code is licensed under the Microsoft Public License. 
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF 
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY 
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR 
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. 
// 
//********************************************************* 
#> 
<#@ template language="C#" debug="false" hostspecific="true"#> 
<#@ include file="EF.Utility.CS.ttinclude"#><#@ 
output extension=".cs"#><# 

CodeGenerationTools code = new CodeGenerationTools(this); 
MetadataLoader loader = new MetadataLoader(this); 
CodeRegion region = new CodeRegion(this, 1); 
MetadataTools ef = new MetadataTools(this); 

string inputFile = @"PSI.Entities.edmx"; 
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile); 
string namespaceName = code.VsNamespaceSuggestion(); 

EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this); 
WriteHeader(fileManager); 

foreach (var entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name)) 
{ 
    fileManager.StartNewFile(entity.Name + ".cs"); 
    BeginNamespace(namespaceName, code); 
#> 
<#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#>partial class <#=code.Escape(entity)#><#=code.StringBefore(" : ", code.Escape(entity.BaseType))#> 
{ 
<# 
    var propertiesWithDefaultValues = entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity && p.DefaultValue != null); 
    var collectionNavigationProperties = entity.NavigationProperties.Where(np => np.DeclaringType == entity && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many); 
    var complexProperties = entity.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == entity); 

    if (propertiesWithDefaultValues.Any() || collectionNavigationProperties.Any() || complexProperties.Any()) 
    { 
#> 
    public <#=code.Escape(entity)#>() 
    { 
<# 
     foreach (var edmProperty in propertiesWithDefaultValues) 
     { 
#> 
     this.<#=N(code.Escape(edmProperty))#> = <#=code.CreateLiteral(edmProperty.DefaultValue)#>; 
<# 
     } 

     foreach (var navigationProperty in collectionNavigationProperties) 
     { 
#> 
     this.<#=N(code.Escape(navigationProperty))#> = new HashSet<<#=code.Escape(navigationProperty.ToEndMember.GetEntityType())#>>(); 
<# 
     } 

     foreach (var complexProperty in complexProperties) 
     { 
#> 
     this.<#=N(code.Escape(complexProperty))#> = new <#=code.Escape(complexProperty.TypeUsage)#>(); 
<# 
     } 
#> 
    } 

<# 
    } 

    var primitiveProperties = entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity); 
    if (primitiveProperties.Any()) 
    { 
     foreach (var edmProperty in primitiveProperties) 
     { 
      WriteProperty(code, edmProperty); 
     } 
    } 

    if (complexProperties.Any()) 
    { 
#> 

<# 
     foreach(var complexProperty in complexProperties) 
     { 
      WriteProperty(code, complexProperty); 
     } 
    } 

    var navigationProperties = entity.NavigationProperties.Where(np => np.DeclaringType == entity); 
    if (navigationProperties.Any()) 
    { 
#> 

<# 
     foreach (var navigationProperty in navigationProperties) 
     { 
      WriteNavigationProperty(code, navigationProperty); 
     } 
    } 
#> 
} 

<# 
    EndNamespace(namespaceName); 
} 

foreach (var complex in ItemCollection.GetItems<ComplexType>().OrderBy(e => e.Name)) 
{ 
    fileManager.StartNewFile(complex.Name + ".cs"); 
    BeginNamespace(namespaceName, code); 
#> 
<#=Accessibility.ForType(complex)#> partial class <#=code.Escape(complex)#> 
{ 
<# 
    var complexProperties = complex.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == complex); 
    var propertiesWithDefaultValues = complex.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == complex && p.DefaultValue != null); 

    if (propertiesWithDefaultValues.Any() || complexProperties.Any()) 
    { 
#> 
    public <#=code.Escape(complex)#>() 
    { 
<# 
     foreach (var edmProperty in propertiesWithDefaultValues) 
     { 
#> 
     this.<#=N(code.Escape(edmProperty))#> = <#=code.CreateLiteral(edmProperty.DefaultValue)#>; 
<# 
     } 

     foreach (var complexProperty in complexProperties) 
     { 
#> 
     this.<#=N(code.Escape(complexProperty))#> = new <#=code.Escape(complexProperty.TypeUsage)#>(); 
<# 
     } 
#> 
    } 

<# 
    } 

    var primitiveProperties = complex.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == complex); 
    if (primitiveProperties.Any()) 
    { 
     foreach(var edmProperty in primitiveProperties) 
     { 
      WriteProperty(code, edmProperty); 
     } 
    } 

    if (complexProperties.Any()) 
    { 
#> 

<# 
     foreach(var edmProperty in complexProperties) 
     { 
      WriteProperty(code, edmProperty); 
     } 
    } 
#> 
} 

<# 
    EndNamespace(namespaceName); 
} 

if (!VerifyTypesAreCaseInsensitiveUnique(ItemCollection)) 
{ 
    return ""; 
} 

fileManager.Process(); 

#> 
<#+ 
void WriteHeader(EntityFrameworkTemplateFileManager fileManager) 
{ 
    fileManager.StartHeader(); 
#> 
//------------------------------------------------------------------------------ 
// <auto-generated> 
// This code was generated from a template. 
// 
// Manual changes to this file may cause unexpected behavior in your application. 
// Manual changes to this file will be overwritten if the code is regenerated. 
// </auto-generated> 
//------------------------------------------------------------------------------ 

using System; 
using System.Collections.Generic; 

<#+ 
    fileManager.EndBlock(); 
} 

void BeginNamespace(string namespaceName, CodeGenerationTools code) 
{ 
    CodeRegion region = new CodeRegion(this); 
    if (!String.IsNullOrEmpty(namespaceName)) 
    { 
#> 
namespace <#=code.EscapeNamespace(namespaceName)#> 
{ 
<#+ 
     PushIndent(CodeRegion.GetIndent(1)); 
    } 
} 


void EndNamespace(string namespaceName) 
{ 
    if (!String.IsNullOrEmpty(namespaceName)) 
    { 
     PopIndent(); 
#> 
} 
<#+ 
    } 
} 

void WriteProperty(CodeGenerationTools code, EdmProperty edmProperty) 
{ 
    WriteProperty(Accessibility.ForProperty(edmProperty), 
        code.Escape(edmProperty.TypeUsage), 
        code.Escape(edmProperty), 
        code.SpaceAfter(Accessibility.ForGetter(edmProperty)), 
        code.SpaceAfter(Accessibility.ForSetter(edmProperty))); 
} 

void WriteNavigationProperty(CodeGenerationTools code, NavigationProperty navigationProperty) 
{ 
    var endType = code.Escape(navigationProperty.ToEndMember.GetEntityType()); 
    WriteProperty(PropertyVirtualModifier(Accessibility.ForProperty(navigationProperty)), 
        navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType, 
        code.Escape(navigationProperty), 
        code.SpaceAfter(Accessibility.ForGetter(navigationProperty)), 
        code.SpaceAfter(Accessibility.ForSetter(navigationProperty))); 
} 

void WriteProperty(string accessibility, string type, string name, string getterAccessibility, string setterAccessibility) 
{ 
#> 
    <#=accessibility#> <#=type#> <#=N(name)#> { <#=getterAccessibility#>get; <#=setterAccessibility#>set; } 
<#+ 
} 

string PropertyVirtualModifier(string accessibility) 
{ 
    return accessibility + (accessibility != "private" ? " virtual" : ""); 
} 

bool VerifyTypesAreCaseInsensitiveUnique(EdmItemCollection itemCollection) 
{ 
    var alreadySeen = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase); 
    foreach(var type in itemCollection.GetItems<StructuralType>()) 
    { 
     if (!(type is EntityType || type is ComplexType)) 
     { 
      continue; 
     } 

     if (alreadySeen.ContainsKey(type.FullName)) 
     { 
      Error(String.Format(CultureInfo.CurrentCulture, "This template does not support types that differ only by case, the types {0} are not supported", type.FullName)); 
      return false; 
     } 
     else 
     { 
      alreadySeen.Add(type.FullName, true); 
     } 
    } 

    return true; 
} 

private string N(string input) { 
    return System.Text.RegularExpressions.Regex.Replace(input, "(?:_|^)([a-z])", match => match.Groups[1].Value.ToUpper()).Replace("_", ""); 
} 
#> 
+0

POCO 객체가 사용되면 엔티티 (개념 모델에서) 매핑이 속성 이름을 기반으로 이루어 지므로 _just_ 속성 이름 변경이 작동하지 않습니다. 또한 개념 모델 엔터티 속성 이름을 변경하거나 속성을 사용하여 매핑 (POCO-> Entity)을 지정하거나 개념 모델 (CSL)에서 속성 이름을 변경해야합니다. –

1

, 두 개의 서로 다른 스키마, 하나의 매핑 스키마가 있습니다. 할 수있는 일은 개념 스키마를 수정하고 속성 이름을 변경할 수 있지만 EDMX를 새로 고치면이 정보가 지워질 수 있다는 것입니다. 하지만 이렇게하면 템플릿을 전혀 변경할 필요가 없습니다.

+0

당신이 맞습니다. 옵션이지만 중요한 결점은 거의 없습니다. EDM을 새로 고침하는 것이 옳습니다. 2. 수동으로 이름을 변경하는 것은 재미 있지 않습니다. 3. Regex (VS가 아닌)를 사용하여 이름을 변경할 수 없습니다. –

관련 문제