FoghornModel.Context.tt 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. <#@ template language="C#" debug="false" hostspecific="true"#>
  2. <#@ include file="EF.Utility.CS.ttinclude"#><#@
  3. output extension=".cs"#><#
  4. const string inputFile = @"FoghornModel.edmx";
  5. var textTransform = DynamicTextTransformation.Create(this);
  6. var code = new CodeGenerationTools(this);
  7. var ef = new MetadataTools(this);
  8. var typeMapper = new TypeMapper(code, ef, textTransform.Errors);
  9. var loader = new EdmMetadataLoader(textTransform.Host, textTransform.Errors);
  10. var itemCollection = loader.CreateEdmItemCollection(inputFile);
  11. var modelNamespace = loader.GetModelNamespace(inputFile);
  12. var codeStringGenerator = new CodeStringGenerator(code, typeMapper, ef);
  13. var container = itemCollection.OfType<EntityContainer>().FirstOrDefault();
  14. if (container == null)
  15. {
  16. return string.Empty;
  17. }
  18. #>
  19. //------------------------------------------------------------------------------
  20. // <auto-generated>
  21. // <#=GetResourceString("Template_GeneratedCodeCommentLine1")#>
  22. //
  23. // <#=GetResourceString("Template_GeneratedCodeCommentLine2")#>
  24. // <#=GetResourceString("Template_GeneratedCodeCommentLine3")#>
  25. // </auto-generated>
  26. //------------------------------------------------------------------------------
  27. <#
  28. var codeNamespace = code.VsNamespaceSuggestion();
  29. if (!String.IsNullOrEmpty(codeNamespace))
  30. {
  31. #>
  32. namespace <#=code.EscapeNamespace(codeNamespace)#>
  33. {
  34. <#
  35. PushIndent(" ");
  36. }
  37. #>
  38. using System;
  39. using System.Data.Entity;
  40. using System.Data.Entity.Infrastructure;
  41. <#
  42. if (container.FunctionImports.Any())
  43. {
  44. #>
  45. using System.Data.Objects;
  46. using System.Data.Objects.DataClasses;
  47. using System.Linq;
  48. <#
  49. }
  50. #>
  51. <#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext
  52. {
  53. public <#=code.Escape(container)#>()
  54. : base("name=<#=container.Name#>")
  55. {
  56. <#
  57. if (!loader.IsLazyLoadingEnabled(container))
  58. {
  59. #>
  60. this.Configuration.LazyLoadingEnabled = false;
  61. <#
  62. }
  63. #>
  64. }
  65. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  66. {
  67. throw new UnintentionalCodeFirstException();
  68. }
  69. <#
  70. foreach (var entitySet in container.BaseEntitySets.OfType<EntitySet>())
  71. {
  72. #>
  73. <#=codeStringGenerator.DbSet(entitySet)#>
  74. <#
  75. }
  76. foreach (var edmFunction in container.FunctionImports)
  77. {
  78. WriteFunctionImport(typeMapper, codeStringGenerator, edmFunction, modelNamespace, includeMergeOption: false);
  79. }
  80. #>
  81. }
  82. <#
  83. if (!String.IsNullOrEmpty(codeNamespace))
  84. {
  85. PopIndent();
  86. #>
  87. }
  88. <#
  89. }
  90. #>
  91. <#+
  92. private void WriteFunctionImport(TypeMapper typeMapper, CodeStringGenerator codeStringGenerator, EdmFunction edmFunction, string modelNamespace, bool includeMergeOption)
  93. {
  94. if (typeMapper.IsComposable(edmFunction))
  95. {
  96. #>
  97. [EdmFunction("<#=edmFunction.NamespaceName#>", "<#=edmFunction.Name#>")]
  98. <#=codeStringGenerator.ComposableFunctionMethod(edmFunction, modelNamespace)#>
  99. {
  100. <#+
  101. codeStringGenerator.WriteFunctionParameters(edmFunction, WriteFunctionParameter);
  102. #>
  103. <#=codeStringGenerator.ComposableCreateQuery(edmFunction, modelNamespace)#>
  104. }
  105. <#+
  106. }
  107. else
  108. {
  109. #>
  110. <#=codeStringGenerator.FunctionMethod(edmFunction, modelNamespace, includeMergeOption)#>
  111. {
  112. <#+
  113. codeStringGenerator.WriteFunctionParameters(edmFunction, WriteFunctionParameter);
  114. #>
  115. <#=codeStringGenerator.ExecuteFunction(edmFunction, modelNamespace, includeMergeOption)#>
  116. }
  117. <#+
  118. if (typeMapper.GenerateMergeOptionFunction(edmFunction, includeMergeOption))
  119. {
  120. WriteFunctionImport(typeMapper, codeStringGenerator, edmFunction, modelNamespace, includeMergeOption: true);
  121. }
  122. }
  123. }
  124. public void WriteFunctionParameter(string name, string isNotNull, string notNullInit, string nullInit)
  125. {
  126. #>
  127. var <#=name#> = <#=isNotNull#> ?
  128. <#=notNullInit#> :
  129. <#=nullInit#>;
  130. <#+
  131. }
  132. public const string TemplateId = "CSharp_DbContext_Context_EF5";
  133. public class CodeStringGenerator
  134. {
  135. private readonly CodeGenerationTools _code;
  136. private readonly TypeMapper _typeMapper;
  137. private readonly MetadataTools _ef;
  138. public CodeStringGenerator(CodeGenerationTools code, TypeMapper typeMapper, MetadataTools ef)
  139. {
  140. ArgumentNotNull(code, "code");
  141. ArgumentNotNull(typeMapper, "typeMapper");
  142. ArgumentNotNull(ef, "ef");
  143. _code = code;
  144. _typeMapper = typeMapper;
  145. _ef = ef;
  146. }
  147. public string Property(EdmProperty edmProperty)
  148. {
  149. return string.Format(
  150. CultureInfo.InvariantCulture,
  151. "{0} {1} {2} {{ {3}get; {4}set; }}",
  152. Accessibility.ForProperty(edmProperty),
  153. _typeMapper.GetTypeName(edmProperty.TypeUsage),
  154. _code.Escape(edmProperty),
  155. _code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
  156. _code.SpaceAfter(Accessibility.ForSetter(edmProperty)));
  157. }
  158. public string NavigationProperty(NavigationProperty navigationProperty)
  159. {
  160. var endType = _typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType());
  161. return string.Format(
  162. CultureInfo.InvariantCulture,
  163. "{0} {1} {2} {{ {3}get; {4}set; }}",
  164. AccessibilityAndVirtual(Accessibility.ForProperty(navigationProperty)),
  165. navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType,
  166. _code.Escape(navigationProperty),
  167. _code.SpaceAfter(Accessibility.ForGetter(navigationProperty)),
  168. _code.SpaceAfter(Accessibility.ForSetter(navigationProperty)));
  169. }
  170. public string AccessibilityAndVirtual(string accessibility)
  171. {
  172. return accessibility + (accessibility != "private" ? " virtual" : "");
  173. }
  174. public string EntityClassOpening(EntityType entity)
  175. {
  176. return string.Format(
  177. CultureInfo.InvariantCulture,
  178. "{0} {1}partial class {2}{3}",
  179. Accessibility.ForType(entity),
  180. _code.SpaceAfter(_code.AbstractOption(entity)),
  181. _code.Escape(entity),
  182. _code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType)));
  183. }
  184. public string EnumOpening(SimpleType enumType)
  185. {
  186. return string.Format(
  187. CultureInfo.InvariantCulture,
  188. "{0} enum {1} : {2}",
  189. Accessibility.ForType(enumType),
  190. _code.Escape(enumType),
  191. _code.Escape(_typeMapper.UnderlyingClrType(enumType)));
  192. }
  193. public void WriteFunctionParameters(EdmFunction edmFunction, Action<string, string, string, string> writeParameter)
  194. {
  195. var parameters = FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef);
  196. foreach (var parameter in parameters.Where(p => p.NeedsLocalVariable))
  197. {
  198. var isNotNull = parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null";
  199. var notNullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", " + parameter.FunctionParameterName + ")";
  200. var nullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", typeof(" + parameter.RawClrTypeName + "))";
  201. writeParameter(parameter.LocalVariableName, isNotNull, notNullInit, nullInit);
  202. }
  203. }
  204. public string ComposableFunctionMethod(EdmFunction edmFunction, string modelNamespace)
  205. {
  206. var parameters = _typeMapper.GetParameters(edmFunction);
  207. return string.Format(
  208. CultureInfo.InvariantCulture,
  209. "{0} IQueryable<{1}> {2}({3})",
  210. AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)),
  211. _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace),
  212. _code.Escape(edmFunction),
  213. string.Join(", ", parameters.Select(p => p.FunctionParameterType + " " + p.FunctionParameterName).ToArray()));
  214. }
  215. public string ComposableCreateQuery(EdmFunction edmFunction, string modelNamespace)
  216. {
  217. var parameters = _typeMapper.GetParameters(edmFunction);
  218. return string.Format(
  219. CultureInfo.InvariantCulture,
  220. "return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<{0}>(\"[{1}].[{2}]({3})\"{4});",
  221. _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace),
  222. edmFunction.NamespaceName,
  223. edmFunction.Name,
  224. string.Join(", ", parameters.Select(p => "@" + p.EsqlParameterName).ToArray()),
  225. _code.StringBefore(", ", string.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray())));
  226. }
  227. public string FunctionMethod(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption)
  228. {
  229. var parameters = _typeMapper.GetParameters(edmFunction);
  230. var returnType = _typeMapper.GetReturnType(edmFunction);
  231. var paramList = String.Join(", ", parameters.Select(p => p.FunctionParameterType + " " + p.FunctionParameterName).ToArray());
  232. if (includeMergeOption)
  233. {
  234. paramList = _code.StringAfter(paramList, ", ") + "MergeOption mergeOption";
  235. }
  236. return string.Format(
  237. CultureInfo.InvariantCulture,
  238. "{0} {1} {2}({3})",
  239. AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)),
  240. returnType == null ? "int" : "ObjectResult<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">",
  241. _code.Escape(edmFunction),
  242. paramList);
  243. }
  244. public string ExecuteFunction(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption)
  245. {
  246. var parameters = _typeMapper.GetParameters(edmFunction);
  247. var returnType = _typeMapper.GetReturnType(edmFunction);
  248. var callParams = _code.StringBefore(", ", String.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()));
  249. if (includeMergeOption)
  250. {
  251. callParams = ", mergeOption" + callParams;
  252. }
  253. return string.Format(
  254. CultureInfo.InvariantCulture,
  255. "return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction{0}(\"{1}\"{2});",
  256. returnType == null ? "" : "<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">",
  257. edmFunction.Name,
  258. callParams);
  259. }
  260. public string DbSet(EntitySet entitySet)
  261. {
  262. return string.Format(
  263. CultureInfo.InvariantCulture,
  264. "{0} DbSet<{1}> {2} {{ get; set; }}",
  265. Accessibility.ForReadOnlyProperty(entitySet),
  266. _typeMapper.GetTypeName(entitySet.ElementType),
  267. _code.Escape(entitySet));
  268. }
  269. public string UsingDirectives(bool inHeader, bool includeCollections = true)
  270. {
  271. return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion())
  272. ? string.Format(
  273. CultureInfo.InvariantCulture,
  274. "{0}using System;{1}" +
  275. "{2}",
  276. inHeader ? Environment.NewLine : "",
  277. includeCollections ? (Environment.NewLine + "using System.Collections.Generic;") : "",
  278. inHeader ? "" : Environment.NewLine)
  279. : "";
  280. }
  281. }
  282. public class TypeMapper
  283. {
  284. private const string ExternalTypeNameAttributeName = @"http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName";
  285. private readonly System.Collections.IList _errors;
  286. private readonly CodeGenerationTools _code;
  287. private readonly MetadataTools _ef;
  288. public TypeMapper(CodeGenerationTools code, MetadataTools ef, System.Collections.IList errors)
  289. {
  290. ArgumentNotNull(code, "code");
  291. ArgumentNotNull(ef, "ef");
  292. ArgumentNotNull(errors, "errors");
  293. _code = code;
  294. _ef = ef;
  295. _errors = errors;
  296. }
  297. public string GetTypeName(TypeUsage typeUsage)
  298. {
  299. return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null);
  300. }
  301. public string GetTypeName(EdmType edmType)
  302. {
  303. return GetTypeName(edmType, isNullable: null, modelNamespace: null);
  304. }
  305. public string GetTypeName(TypeUsage typeUsage, string modelNamespace)
  306. {
  307. return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace);
  308. }
  309. public string GetTypeName(EdmType edmType, string modelNamespace)
  310. {
  311. return GetTypeName(edmType, isNullable: null, modelNamespace: modelNamespace);
  312. }
  313. public string GetTypeName(EdmType edmType, bool? isNullable, string modelNamespace)
  314. {
  315. if (edmType == null)
  316. {
  317. return null;
  318. }
  319. var collectionType = edmType as CollectionType;
  320. if (collectionType != null)
  321. {
  322. return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>", GetTypeName(collectionType.TypeUsage, modelNamespace));
  323. }
  324. var typeName = _code.Escape(edmType.MetadataProperties
  325. .Where(p => p.Name == ExternalTypeNameAttributeName)
  326. .Select(p => (string)p.Value)
  327. .FirstOrDefault())
  328. ?? (modelNamespace != null && edmType.NamespaceName != modelNamespace ?
  329. _code.CreateFullName(_code.EscapeNamespace(edmType.NamespaceName), _code.Escape(edmType)) :
  330. _code.Escape(edmType));
  331. if (edmType is StructuralType)
  332. {
  333. return typeName;
  334. }
  335. if (edmType is SimpleType)
  336. {
  337. var clrType = UnderlyingClrType(edmType);
  338. if (!IsEnumType(edmType))
  339. {
  340. typeName = _code.Escape(clrType);
  341. }
  342. return clrType.IsValueType && isNullable == true ?
  343. String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>", typeName) :
  344. typeName;
  345. }
  346. throw new ArgumentException("edmType");
  347. }
  348. public Type UnderlyingClrType(EdmType edmType)
  349. {
  350. ArgumentNotNull(edmType, "edmType");
  351. var primitiveType = edmType as PrimitiveType;
  352. if (primitiveType != null)
  353. {
  354. return primitiveType.ClrEquivalentType;
  355. }
  356. if (IsEnumType(edmType))
  357. {
  358. return GetEnumUnderlyingType(edmType).ClrEquivalentType;
  359. }
  360. return typeof(object);
  361. }
  362. public object GetEnumMemberValue(MetadataItem enumMember)
  363. {
  364. ArgumentNotNull(enumMember, "enumMember");
  365. var valueProperty = enumMember.GetType().GetProperty("Value");
  366. return valueProperty == null ? null : valueProperty.GetValue(enumMember, null);
  367. }
  368. public string GetEnumMemberName(MetadataItem enumMember)
  369. {
  370. ArgumentNotNull(enumMember, "enumMember");
  371. var nameProperty = enumMember.GetType().GetProperty("Name");
  372. return nameProperty == null ? null : (string)nameProperty.GetValue(enumMember, null);
  373. }
  374. public System.Collections.IEnumerable GetEnumMembers(EdmType enumType)
  375. {
  376. ArgumentNotNull(enumType, "enumType");
  377. var membersProperty = enumType.GetType().GetProperty("Members");
  378. return membersProperty != null
  379. ? (System.Collections.IEnumerable)membersProperty.GetValue(enumType, null)
  380. : Enumerable.Empty<MetadataItem>();
  381. }
  382. public bool EnumIsFlags(EdmType enumType)
  383. {
  384. ArgumentNotNull(enumType, "enumType");
  385. var isFlagsProperty = enumType.GetType().GetProperty("IsFlags");
  386. return isFlagsProperty != null && (bool)isFlagsProperty.GetValue(enumType, null);
  387. }
  388. public bool IsEnumType(GlobalItem edmType)
  389. {
  390. ArgumentNotNull(edmType, "edmType");
  391. return edmType.GetType().Name == "EnumType";
  392. }
  393. public PrimitiveType GetEnumUnderlyingType(EdmType enumType)
  394. {
  395. ArgumentNotNull(enumType, "enumType");
  396. return (PrimitiveType)enumType.GetType().GetProperty("UnderlyingType").GetValue(enumType, null);
  397. }
  398. public string CreateLiteral(object value)
  399. {
  400. if (value == null || value.GetType() != typeof(TimeSpan))
  401. {
  402. return _code.CreateLiteral(value);
  403. }
  404. return string.Format(CultureInfo.InvariantCulture, "new TimeSpan({0})", ((TimeSpan)value).Ticks);
  405. }
  406. public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable<string> types, string sourceFile)
  407. {
  408. ArgumentNotNull(types, "types");
  409. ArgumentNotNull(sourceFile, "sourceFile");
  410. var hash = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
  411. if (types.Any(item => !hash.Add(item)))
  412. {
  413. _errors.Add(
  414. new CompilerError(sourceFile, -1, -1, "6023",
  415. String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_CaseInsensitiveTypeConflict"))));
  416. return false;
  417. }
  418. return true;
  419. }
  420. public IEnumerable<SimpleType> GetEnumItemsToGenerate(IEnumerable<GlobalItem> itemCollection)
  421. {
  422. return GetItemsToGenerate<SimpleType>(itemCollection)
  423. .Where(e => IsEnumType(e));
  424. }
  425. public IEnumerable<T> GetItemsToGenerate<T>(IEnumerable<GlobalItem> itemCollection) where T: EdmType
  426. {
  427. return itemCollection
  428. .OfType<T>()
  429. .Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName))
  430. .OrderBy(i => i.Name);
  431. }
  432. public IEnumerable<string> GetAllGlobalItems(IEnumerable<GlobalItem> itemCollection)
  433. {
  434. return itemCollection
  435. .Where(i => i is EntityType || i is ComplexType || i is EntityContainer || IsEnumType(i))
  436. .Select(g => GetGlobalItemName(g));
  437. }
  438. public string GetGlobalItemName(GlobalItem item)
  439. {
  440. if (item is EdmType)
  441. {
  442. return ((EdmType)item).Name;
  443. }
  444. else
  445. {
  446. return ((EntityContainer)item).Name;
  447. }
  448. }
  449. public IEnumerable<EdmProperty> GetSimpleProperties(EntityType type)
  450. {
  451. return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type);
  452. }
  453. public IEnumerable<EdmProperty> GetSimpleProperties(ComplexType type)
  454. {
  455. return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type);
  456. }
  457. public IEnumerable<EdmProperty> GetComplexProperties(EntityType type)
  458. {
  459. return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type);
  460. }
  461. public IEnumerable<EdmProperty> GetComplexProperties(ComplexType type)
  462. {
  463. return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type);
  464. }
  465. public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(EntityType type)
  466. {
  467. return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null);
  468. }
  469. public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(ComplexType type)
  470. {
  471. return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null);
  472. }
  473. public IEnumerable<NavigationProperty> GetNavigationProperties(EntityType type)
  474. {
  475. return type.NavigationProperties.Where(np => np.DeclaringType == type);
  476. }
  477. public IEnumerable<NavigationProperty> GetCollectionNavigationProperties(EntityType type)
  478. {
  479. return type.NavigationProperties.Where(np => np.DeclaringType == type && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many);
  480. }
  481. public FunctionParameter GetReturnParameter(EdmFunction edmFunction)
  482. {
  483. ArgumentNotNull(edmFunction, "edmFunction");
  484. var returnParamsProperty = edmFunction.GetType().GetProperty("ReturnParameters");
  485. return returnParamsProperty == null
  486. ? edmFunction.ReturnParameter
  487. : ((IEnumerable<FunctionParameter>)returnParamsProperty.GetValue(edmFunction, null)).FirstOrDefault();
  488. }
  489. public bool IsComposable(EdmFunction edmFunction)
  490. {
  491. ArgumentNotNull(edmFunction, "edmFunction");
  492. var isComposableProperty = edmFunction.GetType().GetProperty("IsComposableAttribute");
  493. return isComposableProperty != null && (bool)isComposableProperty.GetValue(edmFunction, null);
  494. }
  495. public IEnumerable<FunctionImportParameter> GetParameters(EdmFunction edmFunction)
  496. {
  497. return FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef);
  498. }
  499. public TypeUsage GetReturnType(EdmFunction edmFunction)
  500. {
  501. var returnParam = GetReturnParameter(edmFunction);
  502. return returnParam == null ? null : _ef.GetElementType(returnParam.TypeUsage);
  503. }
  504. public bool GenerateMergeOptionFunction(EdmFunction edmFunction, bool includeMergeOption)
  505. {
  506. var returnType = GetReturnType(edmFunction);
  507. return !includeMergeOption && returnType != null && returnType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType;
  508. }
  509. }
  510. public class EdmMetadataLoader
  511. {
  512. private readonly IDynamicHost _host;
  513. private readonly System.Collections.IList _errors;
  514. public EdmMetadataLoader(IDynamicHost host, System.Collections.IList errors)
  515. {
  516. ArgumentNotNull(host, "host");
  517. ArgumentNotNull(errors, "errors");
  518. _host = host;
  519. _errors = errors;
  520. }
  521. public IEnumerable<GlobalItem> CreateEdmItemCollection(string sourcePath)
  522. {
  523. ArgumentNotNull(sourcePath, "sourcePath");
  524. if (!ValidateInputPath(sourcePath))
  525. {
  526. return new EdmItemCollection();
  527. }
  528. var schemaElement = LoadRootElement(_host.ResolvePath(sourcePath));
  529. if (schemaElement != null)
  530. {
  531. using (var reader = schemaElement.CreateReader())
  532. {
  533. IList<EdmSchemaError> errors;
  534. var itemCollection = MetadataItemCollectionFactory.CreateEdmItemCollection(new[] { reader }, out errors);
  535. ProcessErrors(errors, sourcePath);
  536. return itemCollection;
  537. }
  538. }
  539. return new EdmItemCollection();
  540. }
  541. public string GetModelNamespace(string sourcePath)
  542. {
  543. ArgumentNotNull(sourcePath, "sourcePath");
  544. if (!ValidateInputPath(sourcePath))
  545. {
  546. return string.Empty;
  547. }
  548. var model = LoadRootElement(_host.ResolvePath(sourcePath));
  549. if (model == null)
  550. {
  551. return string.Empty;
  552. }
  553. var attribute = model.Attribute("Namespace");
  554. return attribute != null ? attribute.Value : "";
  555. }
  556. private bool ValidateInputPath(string sourcePath)
  557. {
  558. if (sourcePath == "$" + "edmxInputFile" + "$")
  559. {
  560. _errors.Add(
  561. new CompilerError(_host.TemplateFile ?? sourcePath, 0, 0, string.Empty,
  562. GetResourceString("Template_ReplaceVsItemTemplateToken")));
  563. return false;
  564. }
  565. return true;
  566. }
  567. public XElement LoadRootElement(string sourcePath)
  568. {
  569. ArgumentNotNull(sourcePath, "sourcePath");
  570. var root = XElement.Load(sourcePath, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo);
  571. return root.Elements()
  572. .Where(e => e.Name.LocalName == "Runtime")
  573. .Elements()
  574. .Where(e => e.Name.LocalName == "ConceptualModels")
  575. .Elements()
  576. .Where(e => e.Name.LocalName == "Schema")
  577. .FirstOrDefault()
  578. ?? root;
  579. }
  580. private void ProcessErrors(IEnumerable<EdmSchemaError> errors, string sourceFilePath)
  581. {
  582. foreach (var error in errors)
  583. {
  584. _errors.Add(
  585. new CompilerError(
  586. error.SchemaLocation ?? sourceFilePath,
  587. error.Line,
  588. error.Column,
  589. error.ErrorCode.ToString(CultureInfo.InvariantCulture),
  590. error.Message)
  591. {
  592. IsWarning = error.Severity == EdmSchemaErrorSeverity.Warning
  593. });
  594. }
  595. }
  596. public bool IsLazyLoadingEnabled(EntityContainer container)
  597. {
  598. string lazyLoadingAttributeValue;
  599. var lazyLoadingAttributeName = MetadataConstants.EDM_ANNOTATION_09_02 + ":LazyLoadingEnabled";
  600. bool isLazyLoading;
  601. return !MetadataTools.TryGetStringMetadataPropertySetting(container, lazyLoadingAttributeName, out lazyLoadingAttributeValue)
  602. || !bool.TryParse(lazyLoadingAttributeValue, out isLazyLoading)
  603. || isLazyLoading;
  604. }
  605. }
  606. public static void ArgumentNotNull<T>(T arg, string name) where T : class
  607. {
  608. if (arg == null)
  609. {
  610. throw new ArgumentNullException(name);
  611. }
  612. }
  613. private static readonly Lazy<System.Resources.ResourceManager> ResourceManager =
  614. new Lazy<System.Resources.ResourceManager>(
  615. () => new System.Resources.ResourceManager("System.Data.Entity.Design", typeof(MetadataItemCollectionFactory).Assembly), isThreadSafe: true);
  616. public static string GetResourceString(string resourceName)
  617. {
  618. ArgumentNotNull(resourceName, "resourceName");
  619. return ResourceManager.Value.GetString(resourceName, null);
  620. }
  621. #>