Advertisement
Guest User

EF T4 Template Customizations Intro

a guest
Jul 18th, 2015
398
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 24.51 KB | None | 0 0
  1. <#@ template language="C#" debug="false" hostspecific="true"#>
  2. <#@ include file="EF6.Utility.CS.ttinclude"#><#@
  3.  output extension=".cs"#><#
  4.  
  5. const string inputFile = @"DriveThruData.edmx";
  6. var textTransform = DynamicTextTransformation.Create(this);
  7. var code = new CodeGenerationTools(this);
  8. var ef = new MetadataTools(this);
  9. var typeMapper = new TypeMapper(code, ef, textTransform.Errors);
  10. var fileManager = EntityFrameworkTemplateFileManager.Create(this);
  11. var itemCollection = new EdmMetadataLoader(textTransform.Host, textTransform.Errors).CreateEdmItemCollection(inputFile);
  12. var codeStringGenerator = new CodeStringGenerator(code, typeMapper, ef);
  13.  
  14. if (!typeMapper.VerifyCaseInsensitiveTypeUniqueness(typeMapper.GetAllGlobalItems(itemCollection), inputFile))
  15. {
  16.     return string.Empty;
  17. }
  18.  
  19. WriteHeader(codeStringGenerator, fileManager);
  20.  
  21. foreach (var entity in typeMapper.GetItemsToGenerate<EntityType>(itemCollection))
  22. {
  23.     fileManager.StartNewFile(entity.Name + ".cs");
  24.     BeginNamespace(code);
  25. #>
  26. <#=codeStringGenerator.UsingDirectives(inHeader: false)#>
  27. <#=codeStringGenerator.EntityClassOpening(entity)#>
  28. {
  29. <#
  30.     var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(entity);
  31.     var collectionNavigationProperties = typeMapper.GetCollectionNavigationProperties(entity);
  32.     var complexProperties = typeMapper.GetComplexProperties(entity);
  33.  
  34.     if (propertiesWithDefaultValues.Any() || collectionNavigationProperties.Any() || complexProperties.Any())
  35.     {
  36. #>
  37.     public <#=code.Escape(entity)#>()
  38.     {
  39.     <#
  40.         foreach (var edmProperty in propertiesWithDefaultValues)
  41.         {
  42. #>
  43.         this.<#=code.Escape(edmProperty)#> = <#=typeMapper.CreateLiteral(edmProperty.DefaultValue)#>;
  44. <#
  45.         }
  46.  
  47.         foreach (var navigationProperty in collectionNavigationProperties)
  48.         {
  49. #>
  50.         this.<#=code.Escape(navigationProperty)#> = new HashSet<<#=typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType())#>>();
  51. <#
  52.         }
  53.  
  54.         foreach (var complexProperty in complexProperties)
  55.         {
  56. #>
  57.         this.<#=code.Escape(complexProperty)#> = new <#=typeMapper.GetTypeName(complexProperty.TypeUsage)#>();
  58. <#
  59.         }
  60. #>
  61.     }
  62.  
  63. <#
  64.     }
  65.  
  66.     var simpleProperties = typeMapper.GetSimpleProperties(entity);
  67.     if (simpleProperties.Any())
  68.     {
  69.         foreach (var edmProperty in simpleProperties)
  70.         {
  71.         if(edmProperty.MaxLength.HasValue)
  72.         {
  73.             #>
  74.  
  75.             public const int <#= edmProperty.Name #>_MAX_LENGTH = <#= edmProperty.MaxLength.Value #>;
  76.  
  77.             <#
  78.         }
  79.     #>
  80.  
  81.     public const string <#= edmProperty.Name #>_Name = "<#= edmProperty.Name #>";
  82.  
  83.     <#=codeStringGenerator.Property(edmProperty)#>
  84.     <#
  85.         }
  86.     }
  87.  
  88.     if (complexProperties.Any())
  89.     {
  90. #>
  91.  
  92. <#
  93.         foreach(var complexProperty in complexProperties)
  94.         {
  95. #>
  96.     <#=codeStringGenerator.Property(complexProperty)#>
  97. <#
  98.         }
  99.     }
  100.  
  101.     var navigationProperties = typeMapper.GetNavigationProperties(entity);
  102.     if (navigationProperties.Any())
  103.     {
  104. #>
  105.  
  106. <#
  107.         foreach (var navigationProperty in navigationProperties)
  108.         {
  109. #>
  110.     <#=codeStringGenerator.NavigationProperty(navigationProperty)#>
  111. <#
  112.         }
  113.     }
  114. #>
  115. }
  116. <#
  117.     EndNamespace(code);
  118. }
  119.  
  120. foreach (var complex in typeMapper.GetItemsToGenerate<ComplexType>(itemCollection))
  121. {
  122.     fileManager.StartNewFile(complex.Name + ".cs");
  123.     BeginNamespace(code);
  124. #>
  125. <#=codeStringGenerator.UsingDirectives(inHeader: false, includeCollections: false)#>
  126. <#=Accessibility.ForType(complex)#> partial class <#=code.Escape(complex)#>
  127. {
  128. <#
  129.     var complexProperties = typeMapper.GetComplexProperties(complex);
  130.     var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(complex);
  131.  
  132.     if (propertiesWithDefaultValues.Any() || complexProperties.Any())
  133.     {
  134. #>
  135.     public <#=code.Escape(complex)#>()
  136.     {
  137. <#
  138.         foreach (var edmProperty in propertiesWithDefaultValues)
  139.         {
  140. #>
  141.         this.<#=code.Escape(edmProperty)#> = <#=typeMapper.CreateLiteral(edmProperty.DefaultValue)#>;
  142. <#
  143.         }
  144.  
  145.         foreach (var complexProperty in complexProperties)
  146.         {
  147. #>
  148.         this.<#=code.Escape(complexProperty)#> = new <#=typeMapper.GetTypeName(complexProperty.TypeUsage)#>();
  149. <#
  150.         }
  151. #>
  152.     }
  153.  
  154. <#
  155.     }
  156.  
  157.     var simpleProperties = typeMapper.GetSimpleProperties(complex);
  158.     if (simpleProperties.Any())
  159.     {
  160.         foreach(var edmProperty in simpleProperties)
  161.         {
  162. #>
  163.     <#=codeStringGenerator.Property(edmProperty)#>
  164. <#
  165.         }
  166.     }
  167.  
  168.     if (complexProperties.Any())
  169.     {
  170. #>
  171.  
  172. <#
  173.         foreach(var edmProperty in complexProperties)
  174.         {
  175. #>
  176.     <#=codeStringGenerator.Property(edmProperty)#>
  177. <#
  178.         }
  179.     }
  180. #>
  181. }
  182. <#
  183.     EndNamespace(code);
  184. }
  185.  
  186. foreach (var enumType in typeMapper.GetEnumItemsToGenerate(itemCollection))
  187. {
  188.     fileManager.StartNewFile(enumType.Name + ".cs");
  189.     BeginNamespace(code);
  190. #>
  191. <#=codeStringGenerator.UsingDirectives(inHeader: false, includeCollections: false)#>
  192. <#
  193.     if (typeMapper.EnumIsFlags(enumType))
  194.     {
  195. #>
  196. [Flags]
  197. <#
  198.     }
  199. #>
  200. <#=codeStringGenerator.EnumOpening(enumType)#>
  201. {
  202. <#
  203.     var foundOne = false;
  204.    
  205.     foreach (MetadataItem member in typeMapper.GetEnumMembers(enumType))
  206.     {
  207.         foundOne = true;
  208. #>
  209.     <#=code.Escape(typeMapper.GetEnumMemberName(member))#> = <#=typeMapper.GetEnumMemberValue(member)#>,
  210. <#
  211.     }
  212.  
  213.     if (foundOne)
  214.     {
  215.         this.GenerationEnvironment.Remove(this.GenerationEnvironment.Length - 3, 1);
  216.     }
  217. #>
  218. }
  219. <#
  220.     EndNamespace(code);
  221. }
  222.  
  223. fileManager.Process();
  224.  
  225. #>
  226. <#+
  227.  
  228. public void WriteHeader(CodeStringGenerator codeStringGenerator, EntityFrameworkTemplateFileManager fileManager)
  229. {
  230.     fileManager.StartHeader();
  231. #>
  232. //------------------------------------------------------------------------------
  233. // <auto-generated>
  234. // <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine1")#>
  235. //
  236. // <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine2")#>
  237. // <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine3")#>
  238. // </auto-generated>
  239. //------------------------------------------------------------------------------
  240. <#=codeStringGenerator.UsingDirectives(inHeader: true)#>
  241. <#+
  242.     fileManager.EndBlock();
  243. }
  244.  
  245. public void BeginNamespace(CodeGenerationTools code)
  246. {
  247.     var codeNamespace = code.VsNamespaceSuggestion();
  248.     if (!String.IsNullOrEmpty(codeNamespace))
  249.     {
  250. #>
  251. namespace <#=code.EscapeNamespace(codeNamespace)#>
  252. {
  253. <#+
  254.         PushIndent("    ");
  255.     }
  256. }
  257.  
  258. public void EndNamespace(CodeGenerationTools code)
  259. {
  260.     if (!String.IsNullOrEmpty(code.VsNamespaceSuggestion()))
  261.     {
  262.         PopIndent();
  263. #>
  264. }
  265. <#+
  266.     }
  267. }
  268.  
  269. public const string TemplateId = "CSharp_DbContext_Types_EF6";
  270.  
  271. public class CodeStringGenerator
  272. {
  273.     private readonly CodeGenerationTools _code;
  274.     private readonly TypeMapper _typeMapper;
  275.     private readonly MetadataTools _ef;
  276.  
  277.     public CodeStringGenerator(CodeGenerationTools code, TypeMapper typeMapper, MetadataTools ef)
  278.     {
  279.         ArgumentNotNull(code, "code");
  280.         ArgumentNotNull(typeMapper, "typeMapper");
  281.         ArgumentNotNull(ef, "ef");
  282.  
  283.         _code = code;
  284.         _typeMapper = typeMapper;
  285.         _ef = ef;
  286.     }
  287.  
  288.     public string Property(EdmProperty edmProperty)
  289.     {
  290.         return string.Format(
  291.             CultureInfo.InvariantCulture,
  292.             "{0} {1} {2} {{ {3}get; {4}set; }}",
  293.             Accessibility.ForProperty(edmProperty),
  294.             _typeMapper.GetTypeName(edmProperty.TypeUsage),
  295.             _code.Escape(edmProperty),
  296.             _code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
  297.             _code.SpaceAfter(Accessibility.ForSetter(edmProperty)));
  298.     }
  299.  
  300.     public string NavigationProperty(NavigationProperty navProp)
  301.     {
  302.         var endType = _typeMapper.GetTypeName(navProp.ToEndMember.GetEntityType());
  303.         return string.Format(
  304.             CultureInfo.InvariantCulture,
  305.             "{0} {1} {2} {{ {3}get; {4}set; }}",
  306.             AccessibilityAndVirtual(Accessibility.ForNavigationProperty(navProp)),
  307.             navProp.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType,
  308.             _code.Escape(navProp),
  309.             _code.SpaceAfter(Accessibility.ForGetter(navProp)),
  310.             _code.SpaceAfter(Accessibility.ForSetter(navProp)));
  311.     }
  312.    
  313.     public string AccessibilityAndVirtual(string accessibility)
  314.     {
  315.         return accessibility + (accessibility != "private" ? " virtual" : "");
  316.     }
  317.    
  318.     public string EntityClassOpening(EntityType entity)
  319.     {
  320.         return string.Format(
  321.             CultureInfo.InvariantCulture,
  322.             "{0} {1}partial class {2}{3}",
  323.             Accessibility.ForType(entity),
  324.             _code.SpaceAfter(_code.AbstractOption(entity)),
  325.             _code.Escape(entity),
  326.             _code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType)));
  327.     }
  328.    
  329.     public string EnumOpening(SimpleType enumType)
  330.     {
  331.         return string.Format(
  332.             CultureInfo.InvariantCulture,
  333.             "{0} enum {1} : {2}",
  334.             Accessibility.ForType(enumType),
  335.             _code.Escape(enumType),
  336.             _code.Escape(_typeMapper.UnderlyingClrType(enumType)));
  337.         }
  338.    
  339.     public void WriteFunctionParameters(EdmFunction edmFunction, Action<string, string, string, string> writeParameter)
  340.     {
  341.         var parameters = FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef);
  342.         foreach (var parameter in parameters.Where(p => p.NeedsLocalVariable))
  343.         {
  344.             var isNotNull = parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null";
  345.             var notNullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", " + parameter.FunctionParameterName + ")";
  346.             var nullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", typeof(" + TypeMapper.FixNamespaces(parameter.RawClrTypeName) + "))";
  347.             writeParameter(parameter.LocalVariableName, isNotNull, notNullInit, nullInit);
  348.         }
  349.     }
  350.    
  351.     public string ComposableFunctionMethod(EdmFunction edmFunction, string modelNamespace)
  352.     {
  353.         var parameters = _typeMapper.GetParameters(edmFunction);
  354.        
  355.         return string.Format(
  356.             CultureInfo.InvariantCulture,
  357.             "{0} IQueryable<{1}> {2}({3})",
  358.             AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)),
  359.             _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace),
  360.             _code.Escape(edmFunction),
  361.             string.Join(", ", parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray()));
  362.     }
  363.    
  364.     public string ComposableCreateQuery(EdmFunction edmFunction, string modelNamespace)
  365.     {
  366.         var parameters = _typeMapper.GetParameters(edmFunction);
  367.        
  368.         return string.Format(
  369.             CultureInfo.InvariantCulture,
  370.             "return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<{0}>(\"[{1}].[{2}]({3})\"{4});",
  371.             _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace),
  372.             edmFunction.NamespaceName,
  373.             edmFunction.Name,
  374.             string.Join(", ", parameters.Select(p => "@" + p.EsqlParameterName).ToArray()),
  375.             _code.StringBefore(", ", string.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray())));
  376.     }
  377.    
  378.     public string FunctionMethod(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption)
  379.     {
  380.         var parameters = _typeMapper.GetParameters(edmFunction);
  381.         var returnType = _typeMapper.GetReturnType(edmFunction);
  382.  
  383.         var paramList = String.Join(", ", parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray());
  384.         if (includeMergeOption)
  385.         {
  386.             paramList = _code.StringAfter(paramList, ", ") + "MergeOption mergeOption";
  387.         }
  388.  
  389.         return string.Format(
  390.             CultureInfo.InvariantCulture,
  391.             "{0} {1} {2}({3})",
  392.             AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)),
  393.             returnType == null ? "int" : "ObjectResult<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">",
  394.             _code.Escape(edmFunction),
  395.             paramList);
  396.     }
  397.    
  398.     public string ExecuteFunction(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption)
  399.     {
  400.         var parameters = _typeMapper.GetParameters(edmFunction);
  401.         var returnType = _typeMapper.GetReturnType(edmFunction);
  402.  
  403.         var callParams = _code.StringBefore(", ", String.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()));
  404.         if (includeMergeOption)
  405.         {
  406.             callParams = ", mergeOption" + callParams;
  407.         }
  408.        
  409.         return string.Format(
  410.             CultureInfo.InvariantCulture,
  411.             "return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction{0}(\"{1}\"{2});",
  412.             returnType == null ? "" : "<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">",
  413.             edmFunction.Name,
  414.             callParams);
  415.     }
  416.    
  417.     public string DbSet(EntitySet entitySet)
  418.     {
  419.         return string.Format(
  420.             CultureInfo.InvariantCulture,
  421.             "{0} virtual DbSet<{1}> {2} {{ get; set; }}",
  422.             Accessibility.ForReadOnlyProperty(entitySet),
  423.             _typeMapper.GetTypeName(entitySet.ElementType),
  424.             _code.Escape(entitySet));
  425.     }
  426.  
  427.     public string UsingDirectives(bool inHeader, bool includeCollections = true)
  428.     {
  429.         return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion())
  430.             ? string.Format(
  431.                 CultureInfo.InvariantCulture,
  432.                 "{0}using System;{1}" +
  433.                 "{2}",
  434.                 inHeader ? Environment.NewLine : "",
  435.                 includeCollections ? (Environment.NewLine + "using System.Collections.Generic;") : "",
  436.                 inHeader ? "" : Environment.NewLine)
  437.             : "";
  438.     }
  439. }
  440.  
  441. public class TypeMapper
  442. {
  443.     private const string ExternalTypeNameAttributeName = @"http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName";
  444.  
  445.     private readonly System.Collections.IList _errors;
  446.     private readonly CodeGenerationTools _code;
  447.     private readonly MetadataTools _ef;
  448.  
  449.     public TypeMapper(CodeGenerationTools code, MetadataTools ef, System.Collections.IList errors)
  450.     {
  451.         ArgumentNotNull(code, "code");
  452.         ArgumentNotNull(ef, "ef");
  453.         ArgumentNotNull(errors, "errors");
  454.  
  455.         _code = code;
  456.         _ef = ef;
  457.         _errors = errors;
  458.     }
  459.  
  460.     public static string FixNamespaces(string typeName)
  461.     {
  462.         return typeName.Replace("System.Data.Spatial.", "System.Data.Entity.Spatial.");
  463.     }
  464.  
  465.     public string GetTypeName(TypeUsage typeUsage)
  466.     {
  467.         return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null);
  468.     }
  469.  
  470.     public string GetTypeName(EdmType edmType)
  471.     {
  472.         return GetTypeName(edmType, isNullable: null, modelNamespace: null);
  473.     }
  474.  
  475.     public string GetTypeName(TypeUsage typeUsage, string modelNamespace)
  476.     {
  477.         return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace);
  478.     }
  479.  
  480.     public string GetTypeName(EdmType edmType, string modelNamespace)
  481.     {
  482.         return GetTypeName(edmType, isNullable: null, modelNamespace: modelNamespace);
  483.     }
  484.  
  485.     public string GetTypeName(EdmType edmType, bool? isNullable, string modelNamespace)
  486.     {
  487.         if (edmType == null)
  488.         {
  489.             return null;
  490.         }
  491.  
  492.         var collectionType = edmType as CollectionType;
  493.         if (collectionType != null)
  494.         {
  495.             return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>", GetTypeName(collectionType.TypeUsage, modelNamespace));
  496.         }
  497.  
  498.         var typeName = _code.Escape(edmType.MetadataProperties
  499.                                 .Where(p => p.Name == ExternalTypeNameAttributeName)
  500.                                 .Select(p => (string)p.Value)
  501.                                 .FirstOrDefault())
  502.             ?? (modelNamespace != null && edmType.NamespaceName != modelNamespace ?
  503.                 _code.CreateFullName(_code.EscapeNamespace(edmType.NamespaceName), _code.Escape(edmType)) :
  504.                 _code.Escape(edmType));
  505.  
  506.         if (edmType is StructuralType)
  507.         {
  508.             return typeName;
  509.         }
  510.  
  511.         if (edmType is SimpleType)
  512.         {
  513.             var clrType = UnderlyingClrType(edmType);
  514.             if (!IsEnumType(edmType))
  515.             {
  516.                 typeName = _code.Escape(clrType);
  517.             }
  518.  
  519.             typeName = FixNamespaces(typeName);
  520.  
  521.             return clrType.IsValueType && isNullable == true ?
  522.                 String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>", typeName) :
  523.                 typeName;
  524.         }
  525.  
  526.         throw new ArgumentException("edmType");
  527.     }
  528.    
  529.     public Type UnderlyingClrType(EdmType edmType)
  530.     {
  531.         ArgumentNotNull(edmType, "edmType");
  532.  
  533.         var primitiveType = edmType as PrimitiveType;
  534.         if (primitiveType != null)
  535.         {
  536.             return primitiveType.ClrEquivalentType;
  537.         }
  538.  
  539.         if (IsEnumType(edmType))
  540.         {
  541.             return GetEnumUnderlyingType(edmType).ClrEquivalentType;
  542.         }
  543.  
  544.         return typeof(object);
  545.     }
  546.    
  547.     public object GetEnumMemberValue(MetadataItem enumMember)
  548.     {
  549.         ArgumentNotNull(enumMember, "enumMember");
  550.        
  551.         var valueProperty = enumMember.GetType().GetProperty("Value");
  552.         return valueProperty == null ? null : valueProperty.GetValue(enumMember, null);
  553.     }
  554.    
  555.     public string GetEnumMemberName(MetadataItem enumMember)
  556.     {
  557.         ArgumentNotNull(enumMember, "enumMember");
  558.        
  559.         var nameProperty = enumMember.GetType().GetProperty("Name");
  560.         return nameProperty == null ? null : (string)nameProperty.GetValue(enumMember, null);
  561.     }
  562.  
  563.     public System.Collections.IEnumerable GetEnumMembers(EdmType enumType)
  564.     {
  565.         ArgumentNotNull(enumType, "enumType");
  566.  
  567.         var membersProperty = enumType.GetType().GetProperty("Members");
  568.         return membersProperty != null
  569.             ? (System.Collections.IEnumerable)membersProperty.GetValue(enumType, null)
  570.             : Enumerable.Empty<MetadataItem>();
  571.     }
  572.    
  573.     public bool EnumIsFlags(EdmType enumType)
  574.     {
  575.         ArgumentNotNull(enumType, "enumType");
  576.        
  577.         var isFlagsProperty = enumType.GetType().GetProperty("IsFlags");
  578.         return isFlagsProperty != null && (bool)isFlagsProperty.GetValue(enumType, null);
  579.     }
  580.  
  581.     public bool IsEnumType(GlobalItem edmType)
  582.     {
  583.         ArgumentNotNull(edmType, "edmType");
  584.  
  585.         return edmType.GetType().Name == "EnumType";
  586.     }
  587.  
  588.     public PrimitiveType GetEnumUnderlyingType(EdmType enumType)
  589.     {
  590.         ArgumentNotNull(enumType, "enumType");
  591.  
  592.         return (PrimitiveType)enumType.GetType().GetProperty("UnderlyingType").GetValue(enumType, null);
  593.     }
  594.  
  595.     public string CreateLiteral(object value)
  596.     {
  597.         if (value == null || value.GetType() != typeof(TimeSpan))
  598.         {
  599.             return _code.CreateLiteral(value);
  600.         }
  601.  
  602.         return string.Format(CultureInfo.InvariantCulture, "new TimeSpan({0})", ((TimeSpan)value).Ticks);
  603.     }
  604.    
  605.     public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable<string> types, string sourceFile)
  606.     {
  607.         ArgumentNotNull(types, "types");
  608.         ArgumentNotNull(sourceFile, "sourceFile");
  609.        
  610.         var hash = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
  611.         if (types.Any(item => !hash.Add(item)))
  612.         {
  613.             _errors.Add(
  614.                 new CompilerError(sourceFile, -1, -1, "6023",
  615.                     String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_CaseInsensitiveTypeConflict"))));
  616.             return false;
  617.         }
  618.         return true;
  619.     }
  620.    
  621.     public IEnumerable<SimpleType> GetEnumItemsToGenerate(IEnumerable<GlobalItem> itemCollection)
  622.     {
  623.         return GetItemsToGenerate<SimpleType>(itemCollection)
  624.             .Where(e => IsEnumType(e));
  625.     }
  626.    
  627.     public IEnumerable<T> GetItemsToGenerate<T>(IEnumerable<GlobalItem> itemCollection) where T: EdmType
  628.     {
  629.         return itemCollection
  630.             .OfType<T>()
  631.             .Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName))
  632.             .OrderBy(i => i.Name);
  633.     }
  634.  
  635.     public IEnumerable<string> GetAllGlobalItems(IEnumerable<GlobalItem> itemCollection)
  636.     {
  637.         return itemCollection
  638.             .Where(i => i is EntityType || i is ComplexType || i is EntityContainer || IsEnumType(i))
  639.             .Select(g => GetGlobalItemName(g));
  640.     }
  641.  
  642.     public string GetGlobalItemName(GlobalItem item)
  643.     {
  644.         if (item is EdmType)
  645.         {
  646.             return ((EdmType)item).Name;
  647.         }
  648.         else
  649.         {
  650.             return ((EntityContainer)item).Name;
  651.         }
  652.     }
  653.  
  654.     public IEnumerable<EdmProperty> GetSimpleProperties(EntityType type)
  655.     {
  656.         return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type);
  657.     }
  658.    
  659.     public IEnumerable<EdmProperty> GetSimpleProperties(ComplexType type)
  660.     {
  661.         return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type);
  662.     }
  663.    
  664.     public IEnumerable<EdmProperty> GetComplexProperties(EntityType type)
  665.     {
  666.         return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type);
  667.     }
  668.    
  669.     public IEnumerable<EdmProperty> GetComplexProperties(ComplexType type)
  670.     {
  671.         return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type);
  672.     }
  673.  
  674.     public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(EntityType type)
  675.     {
  676.         return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null);
  677.     }
  678.    
  679.     public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(ComplexType type)
  680.     {
  681.         return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null);
  682.     }
  683.  
  684.     public IEnumerable<NavigationProperty> GetNavigationProperties(EntityType type)
  685.     {
  686.         return type.NavigationProperties.Where(np => np.DeclaringType == type);
  687.     }
  688.    
  689.     public IEnumerable<NavigationProperty> GetCollectionNavigationProperties(EntityType type)
  690.     {
  691.         return type.NavigationProperties.Where(np => np.DeclaringType == type && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many);
  692.     }
  693.    
  694.     public FunctionParameter GetReturnParameter(EdmFunction edmFunction)
  695.     {
  696.         ArgumentNotNull(edmFunction, "edmFunction");
  697.  
  698.         var returnParamsProperty = edmFunction.GetType().GetProperty("ReturnParameters");
  699.         return returnParamsProperty == null
  700.             ? edmFunction.ReturnParameter
  701.             : ((IEnumerable<FunctionParameter>)returnParamsProperty.GetValue(edmFunction, null)).FirstOrDefault();
  702.     }
  703.  
  704.     public bool IsComposable(EdmFunction edmFunction)
  705.     {
  706.         ArgumentNotNull(edmFunction, "edmFunction");
  707.  
  708.         var isComposableProperty = edmFunction.GetType().GetProperty("IsComposableAttribute");
  709.         return isComposableProperty != null && (bool)isComposableProperty.GetValue(edmFunction, null);
  710.     }
  711.  
  712.     public IEnumerable<FunctionImportParameter> GetParameters(EdmFunction edmFunction)
  713.     {
  714.         return FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef);
  715.     }
  716.  
  717.     public TypeUsage GetReturnType(EdmFunction edmFunction)
  718.     {
  719.         var returnParam = GetReturnParameter(edmFunction);
  720.         return returnParam == null ? null : _ef.GetElementType(returnParam.TypeUsage);
  721.     }
  722.    
  723.     public bool GenerateMergeOptionFunction(EdmFunction edmFunction, bool includeMergeOption)
  724.     {
  725.         var returnType = GetReturnType(edmFunction);
  726.         return !includeMergeOption && returnType != null && returnType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType;
  727.     }
  728. }
  729.  
  730. public static void ArgumentNotNull<T>(T arg, string name) where T : class
  731. {
  732.     if (arg == null)
  733.     {
  734.         throw new ArgumentNullException(name);
  735.     }
  736. }
  737. #>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement