GenericFactories.tt 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. <#@ template language="C#" debug="false" hostspecific="true"#>
  2. <#@ include file="EF6.Utility.CS.ttinclude"#>
  3. <#@ output extension=".cs"#>
  4. <#
  5. const string inputFile = @"../../CD67.FicheCollege.Entity/EntityModel.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. foreach (var entity in typeMapper.GetItemsToGenerate<EntityType>(itemCollection))
  13. {
  14. fileManager.StartNewFile(entity.Name + "Factory.cs");
  15. #>
  16. using CD67.FicheCollege.Entity;
  17. using System.Linq;
  18. namespace CD67.FicheCollege.Factory
  19. {
  20. /// <summary>
  21. /// NE PAS MODIFIER
  22. /// C'est une classe partielle, elle peut être complétée avec une classe partielle du même nom
  23. /// Factory générée automatiquement à l'aide du fichier GenericFactories.tt
  24. /// pour toutes les entités du fichier entity : /CD67.FicheCollege.Entity/EntityModel.edmx
  25. /// </summary>
  26. <#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#>partial class <#=code.Escape(entity)#>Factory : Internal.BaseFactory<Entity.<#=code.Escape(entity)#>>
  27. {
  28. /// <summary>
  29. /// Constructeur public lié au constructeur de base
  30. /// </summary>
  31. /// <param name="dbContext">Context Entity Framework utilisé dans la classe</param>
  32. <#=Accessibility.ForType(entity)#> <#=code.Escape(entity)#>Factory(Entities dbContext) : base(dbContext) { }
  33. }
  34. }
  35. <#
  36. }
  37. fileManager.Process();
  38. #>
  39. <#+
  40. public class TypeMapper
  41. {
  42. private const string ExternalTypeNameAttributeName = @"http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName";
  43. private readonly System.Collections.IList _errors;
  44. private readonly CodeGenerationTools _code;
  45. private readonly MetadataTools _ef;
  46. public TypeMapper(CodeGenerationTools code, MetadataTools ef, System.Collections.IList errors)
  47. {
  48. ArgumentNotNull(code, "code");
  49. ArgumentNotNull(ef, "ef");
  50. ArgumentNotNull(errors, "errors");
  51. _code = code;
  52. _ef = ef;
  53. _errors = errors;
  54. }
  55. public static string FixNamespaces(string typeName)
  56. {
  57. return typeName.Replace("System.Data.Spatial.", "System.Data.Entity.Spatial.");
  58. }
  59. public string GetTypeName(TypeUsage typeUsage)
  60. {
  61. return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null);
  62. }
  63. public string GetTypeName(EdmType edmType)
  64. {
  65. return GetTypeName(edmType, isNullable: null, modelNamespace: null);
  66. }
  67. public string GetTypeName(TypeUsage typeUsage, string modelNamespace)
  68. {
  69. return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace);
  70. }
  71. public string GetTypeName(EdmType edmType, string modelNamespace)
  72. {
  73. return GetTypeName(edmType, isNullable: null, modelNamespace: modelNamespace);
  74. }
  75. public string GetTypeName(EdmType edmType, bool? isNullable, string modelNamespace)
  76. {
  77. if (edmType == null)
  78. {
  79. return null;
  80. }
  81. var collectionType = edmType as CollectionType;
  82. if (collectionType != null)
  83. {
  84. return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>", GetTypeName(collectionType.TypeUsage, modelNamespace));
  85. }
  86. var typeName = _code.Escape(edmType.MetadataProperties
  87. .Where(p => p.Name == ExternalTypeNameAttributeName)
  88. .Select(p => (string)p.Value)
  89. .FirstOrDefault())
  90. ?? (modelNamespace != null && edmType.NamespaceName != modelNamespace ?
  91. _code.CreateFullName(_code.EscapeNamespace(edmType.NamespaceName), _code.Escape(edmType)) :
  92. _code.Escape(edmType));
  93. if (edmType is StructuralType)
  94. {
  95. return typeName;
  96. }
  97. if (edmType is SimpleType)
  98. {
  99. var clrType = UnderlyingClrType(edmType);
  100. if (!IsEnumType(edmType))
  101. {
  102. typeName = _code.Escape(clrType);
  103. }
  104. typeName = FixNamespaces(typeName);
  105. return clrType.IsValueType && isNullable == true ?
  106. String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>", typeName) :
  107. typeName;
  108. }
  109. throw new ArgumentException("edmType");
  110. }
  111. public Type UnderlyingClrType(EdmType edmType)
  112. {
  113. ArgumentNotNull(edmType, "edmType");
  114. var primitiveType = edmType as PrimitiveType;
  115. if (primitiveType != null)
  116. {
  117. return primitiveType.ClrEquivalentType;
  118. }
  119. if (IsEnumType(edmType))
  120. {
  121. return GetEnumUnderlyingType(edmType).ClrEquivalentType;
  122. }
  123. return typeof(object);
  124. }
  125. public object GetEnumMemberValue(MetadataItem enumMember)
  126. {
  127. ArgumentNotNull(enumMember, "enumMember");
  128. var valueProperty = enumMember.GetType().GetProperty("Value");
  129. return valueProperty == null ? null : valueProperty.GetValue(enumMember, null);
  130. }
  131. public string GetEnumMemberName(MetadataItem enumMember)
  132. {
  133. ArgumentNotNull(enumMember, "enumMember");
  134. var nameProperty = enumMember.GetType().GetProperty("Name");
  135. return nameProperty == null ? null : (string)nameProperty.GetValue(enumMember, null);
  136. }
  137. public System.Collections.IEnumerable GetEnumMembers(EdmType enumType)
  138. {
  139. ArgumentNotNull(enumType, "enumType");
  140. var membersProperty = enumType.GetType().GetProperty("Members");
  141. return membersProperty != null
  142. ? (System.Collections.IEnumerable)membersProperty.GetValue(enumType, null)
  143. : Enumerable.Empty<MetadataItem>();
  144. }
  145. public bool EnumIsFlags(EdmType enumType)
  146. {
  147. ArgumentNotNull(enumType, "enumType");
  148. var isFlagsProperty = enumType.GetType().GetProperty("IsFlags");
  149. return isFlagsProperty != null && (bool)isFlagsProperty.GetValue(enumType, null);
  150. }
  151. public bool IsEnumType(GlobalItem edmType)
  152. {
  153. ArgumentNotNull(edmType, "edmType");
  154. return edmType.GetType().Name == "EnumType";
  155. }
  156. public PrimitiveType GetEnumUnderlyingType(EdmType enumType)
  157. {
  158. ArgumentNotNull(enumType, "enumType");
  159. return (PrimitiveType)enumType.GetType().GetProperty("UnderlyingType").GetValue(enumType, null);
  160. }
  161. public string CreateLiteral(object value)
  162. {
  163. if (value == null || value.GetType() != typeof(TimeSpan))
  164. {
  165. return _code.CreateLiteral(value);
  166. }
  167. return string.Format(CultureInfo.InvariantCulture, "new TimeSpan({0})", ((TimeSpan)value).Ticks);
  168. }
  169. public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable<string> types, string sourceFile)
  170. {
  171. ArgumentNotNull(types, "types");
  172. ArgumentNotNull(sourceFile, "sourceFile");
  173. var hash = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
  174. if (types.Any(item => !hash.Add(item)))
  175. {
  176. _errors.Add(
  177. new CompilerError(sourceFile, -1, -1, "6023",
  178. String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_CaseInsensitiveTypeConflict"))));
  179. return false;
  180. }
  181. return true;
  182. }
  183. public IEnumerable<SimpleType> GetEnumItemsToGenerate(IEnumerable<GlobalItem> itemCollection)
  184. {
  185. return GetItemsToGenerate<SimpleType>(itemCollection)
  186. .Where(e => IsEnumType(e));
  187. }
  188. public IEnumerable<T> GetItemsToGenerate<T>(IEnumerable<GlobalItem> itemCollection) where T: EdmType
  189. {
  190. return itemCollection
  191. .OfType<T>()
  192. .Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName))
  193. .OrderBy(i => i.Name);
  194. }
  195. public IEnumerable<string> GetAllGlobalItems(IEnumerable<GlobalItem> itemCollection)
  196. {
  197. return itemCollection
  198. .Where(i => i is EntityType || i is ComplexType || i is EntityContainer || IsEnumType(i))
  199. .Select(g => GetGlobalItemName(g));
  200. }
  201. public string GetGlobalItemName(GlobalItem item)
  202. {
  203. if (item is EdmType)
  204. {
  205. return ((EdmType)item).Name;
  206. }
  207. else
  208. {
  209. return ((EntityContainer)item).Name;
  210. }
  211. }
  212. public IEnumerable<EdmProperty> GetSimpleProperties(EntityType type)
  213. {
  214. return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type);
  215. }
  216. public IEnumerable<EdmProperty> GetSimpleProperties(ComplexType type)
  217. {
  218. return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type);
  219. }
  220. public IEnumerable<EdmProperty> GetComplexProperties(EntityType type)
  221. {
  222. return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type);
  223. }
  224. public IEnumerable<EdmProperty> GetComplexProperties(ComplexType type)
  225. {
  226. return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type);
  227. }
  228. public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(EntityType type)
  229. {
  230. return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null);
  231. }
  232. public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(ComplexType type)
  233. {
  234. return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null);
  235. }
  236. public IEnumerable<NavigationProperty> GetNavigationProperties(EntityType type)
  237. {
  238. return type.NavigationProperties.Where(np => np.DeclaringType == type);
  239. }
  240. public IEnumerable<NavigationProperty> GetCollectionNavigationProperties(EntityType type)
  241. {
  242. return type.NavigationProperties.Where(np => np.DeclaringType == type && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many);
  243. }
  244. public FunctionParameter GetReturnParameter(EdmFunction edmFunction)
  245. {
  246. ArgumentNotNull(edmFunction, "edmFunction");
  247. var returnParamsProperty = edmFunction.GetType().GetProperty("ReturnParameters");
  248. return returnParamsProperty == null
  249. ? edmFunction.ReturnParameter
  250. : ((IEnumerable<FunctionParameter>)returnParamsProperty.GetValue(edmFunction, null)).FirstOrDefault();
  251. }
  252. public bool IsComposable(EdmFunction edmFunction)
  253. {
  254. ArgumentNotNull(edmFunction, "edmFunction");
  255. var isComposableProperty = edmFunction.GetType().GetProperty("IsComposableAttribute");
  256. return isComposableProperty != null && (bool)isComposableProperty.GetValue(edmFunction, null);
  257. }
  258. public IEnumerable<FunctionImportParameter> GetParameters(EdmFunction edmFunction)
  259. {
  260. return FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef);
  261. }
  262. public TypeUsage GetReturnType(EdmFunction edmFunction)
  263. {
  264. var returnParam = GetReturnParameter(edmFunction);
  265. return returnParam == null ? null : _ef.GetElementType(returnParam.TypeUsage);
  266. }
  267. public bool GenerateMergeOptionFunction(EdmFunction edmFunction, bool includeMergeOption)
  268. {
  269. var returnType = GetReturnType(edmFunction);
  270. return !includeMergeOption && returnType != null && returnType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType;
  271. }
  272. }
  273. public static void ArgumentNotNull<T>(T arg, string name) where T : class
  274. {
  275. if (arg == null)
  276. {
  277. throw new ArgumentNullException(name);
  278. }
  279. }
  280. #>