Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <#@ template debug="false" hostSpecific="true" #>
- <#@ include file="EF.Utility.CS.ttinclude"#>
- <#@ output extension=".cs" #>
- <#@ Assembly Name="System.Core" #>
- <#@ Assembly Name="System.Data.Entity" #>
- <#@ Assembly Name="$(SolutionDir)packages\EntityFramework.5.0.0\lib\net45\EntityFramework.dll" #>
- <#@ import namespace="System.Linq" #>
- <#@ import namespace="System.Collections.Generic" #>
- <#@ import namespace="System.Data.Entity.Infrastructure" #>
- <#@ import namespace="System.Data.Metadata.Edm" #>
- <#@ import namespace="System.Data.Entity" #>
- <#
- // settings start
- string inputFile = @"%project%Model.edmx";
- // settings end
- var textTransform = DynamicTextTransformation.Create(this);
- var code = new CodeGenerationTools(this);
- var ef = new MetadataTools(this);
- var typeMapper = new TypeMapper(code, ef, textTransform.Errors);
- var itemCollection = new EdmMetadataLoader(textTransform.Host, textTransform.Errors).CreateEdmItemCollection(inputFile);
- Generate(itemCollection, code, typeMapper);
- #><#+
- void Generate(IEnumerable<GlobalItem> itemCollection, CodeGenerationTools code, TypeMapper typeMapper)
- {
- ArgumentNotNull(itemCollection, "itemCollection");
- ArgumentNotNull(code, "code");
- var codeNamespace = code.VsNamespaceSuggestion();
- #>
- #pragma warning disable 649 // disable compiler warnings about unassigned fields
- namespace <#= code.EscapeNamespace(codeNamespace) #>
- {
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.ComponentModel.DataAnnotations;
- using System.Data.Objects.DataClasses;
- using System.Linq;
- using System.Runtime.Serialization;
- using System.ServiceModel.DomainServices.Hosting;
- using System.ServiceModel.DomainServices.Server;
- using RIAServices.M2M;
- <#+
- var container = itemCollection.OfType<EntityContainer>().First();
- var associations = container.BaseEntitySets
- .Where(es => es.BuiltInTypeKind == BuiltInTypeKind.EntitySet)
- .OfType<EntitySet>()
- .SelectMany(es => es.ElementType.NavigationProperties)
- .Where(np => np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many && np.FromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many);
- var entities = itemCollection.OfType<EntityType>();
- foreach (var elementType in entities)//container.BaseEntitySets.Where(set => set.BuiltInTypeKind == BuiltInTypeKind.EntitySet))
- {
- string elementName = code.Escape(elementType.Name);
- string summary = elementType.Documentation != null ? elementType.Documentation.Summary : null;
- if (!string.IsNullOrEmpty(summary))
- {
- #>
- /// <summary>
- /// <#= summary #>
- /// </summary>
- <#+
- }
- // http://msdn.microsoft.com/en-us/library/ee707366%28v=vs.91%29.aspx
- var knownTypes = entities.Where(e => e.BaseType == elementType);
- if (knownTypes.Count() > 0)
- {
- string knownLine = "";
- var last = knownTypes.Last();
- foreach (var knownType in knownTypes)
- {
- knownLine += "KnownType(typeof(" + code.Escape(knownType.Name) + "))";
- if (knownType != last)
- knownLine += ", ";
- }
- #>
- [<#= knownLine #>]
- <#+
- }
- #>
- [MetadataTypeAttribute(typeof(<#= elementName #>.<#= elementName #>Metadata))]
- public partial class <#= elementName #>
- {
- internal sealed class <#= elementName #>Metadata
- {
- private <#= elementName #>Metadata() { }
- <#+
- var members = elementType.Members.AsEnumerable();
- if (elementType.BaseType != null && elementType.BaseType is StructuralType)
- members = members.Except(((StructuralType)elementType.BaseType).Members);
- foreach (var member in members)
- {
- WriteLine("");
- summary = member.Documentation != null ? member.Documentation.Summary : null;
- if (!string.IsNullOrEmpty(summary))
- {
- #>
- [Display(Name="<#= summary #>")]
- <#+
- }
- if (elementType.KeyMembers.Contains(member))
- {
- #>
- [Key]
- <#+
- }
- if (member.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType || member.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.CollectionType)
- {
- if (!associations.Contains(member))
- {
- #>
- [Include]
- <#+
- }
- }
- string type = typeMapper.GetTypeName(member.TypeUsage);
- if (member is EdmProperty && ((EdmProperty)member).Nullable == false)
- {
- #>
- [Required(ErrorMessage="Значение не может быть пустым")]
- <#+
- }
- #>
- public <#= type #> <#= code.Escape(member.Name) #>;
- <#+
- }
- #>
- }
- }
- <#+
- }
- // M2M support http://m2m4ria.codeplex.com/wikipage?title=Step-by-step%20instructions%20for%20using%20M2M%20with%20WCR%20RIA%20Services
- foreach (var propertiesGroup in associations.GroupBy(np => np.RelationshipType))
- {
- var relationship = propertiesGroup.Key;
- var className = code.Escape("M2M_" + relationship.Name);
- var type1 = relationship.RelationshipEndMembers.First().GetEntityType();
- var type2 = relationship.RelationshipEndMembers.Last().GetEntityType();
- #>
- public class <#= className #> : LinkTable<<#= code.Escape(type1.Name) #>, <#= code.Escape(type2.Name) #>> { }
- <#+
- foreach (var property in propertiesGroup)
- {
- #>
- public partial class <#= code.Escape(property.DeclaringType.Name) #>
- {
- [Include]
- public ICollection<<#= className #>> <#= className #>
- {
- get
- {
- return <#= code.Escape(property.Name) #>.ToLinkTable<<#= code.Escape(type1.Name) #>, <#= code.Escape(type2.Name) #>, <#= className #>>(this);
- }
- }
- }
- <#+
- }
- }
- #>
- }
- #pragma warning restore 649 // re-enable compiler warnings about unassigned fields
- <#+
- }
- public class TypeMapper
- {
- private const string ExternalTypeNameAttributeName = @"http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName";
- private readonly System.Collections.IList _errors;
- private readonly CodeGenerationTools _code;
- private readonly MetadataTools _ef;
- public TypeMapper(CodeGenerationTools code, MetadataTools ef, System.Collections.IList errors)
- {
- ArgumentNotNull(code, "code");
- ArgumentNotNull(ef, "ef");
- ArgumentNotNull(errors, "errors");
- _code = code;
- _ef = ef;
- _errors = errors;
- }
- public string GetTypeName(TypeUsage typeUsage)
- {
- return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null);
- }
- public string GetTypeName(EdmType edmType)
- {
- return GetTypeName(edmType, isNullable: null, modelNamespace: null);
- }
- public string GetTypeName(TypeUsage typeUsage, string modelNamespace)
- {
- return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace);
- }
- public string GetTypeName(EdmType edmType, string modelNamespace)
- {
- return GetTypeName(edmType, isNullable: null, modelNamespace: modelNamespace);
- }
- public string GetTypeName(EdmType edmType, bool? isNullable, string modelNamespace)
- {
- if (edmType == null)
- {
- return null;
- }
- var collectionType = edmType as CollectionType;
- if (collectionType != null)
- {
- return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>", GetTypeName(collectionType.TypeUsage, modelNamespace));
- }
- var typeName = _code.Escape(edmType.MetadataProperties
- .Where(p => p.Name == ExternalTypeNameAttributeName)
- .Select(p => (string)p.Value)
- .FirstOrDefault())
- ?? (modelNamespace != null && edmType.NamespaceName != modelNamespace ?
- _code.CreateFullName(_code.EscapeNamespace(edmType.NamespaceName), _code.Escape(edmType)) :
- _code.Escape(edmType));
- if (edmType is StructuralType)
- {
- return typeName;
- }
- if (edmType is SimpleType)
- {
- var clrType = UnderlyingClrType(edmType);
- if (!IsEnumType(edmType))
- {
- typeName = _code.Escape(clrType);
- }
- return clrType.IsValueType && isNullable == true ?
- String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>", typeName) :
- typeName;
- }
- throw new ArgumentException("edmType");
- }
- public Type UnderlyingClrType(EdmType edmType)
- {
- ArgumentNotNull(edmType, "edmType");
- var primitiveType = edmType as PrimitiveType;
- if (primitiveType != null)
- {
- return primitiveType.ClrEquivalentType;
- }
- if (IsEnumType(edmType))
- {
- return GetEnumUnderlyingType(edmType).ClrEquivalentType;
- }
- return typeof(object);
- }
- public object GetEnumMemberValue(MetadataItem enumMember)
- {
- ArgumentNotNull(enumMember, "enumMember");
- var valueProperty = enumMember.GetType().GetProperty("Value");
- return valueProperty == null ? null : valueProperty.GetValue(enumMember, null);
- }
- public string GetEnumMemberName(MetadataItem enumMember)
- {
- ArgumentNotNull(enumMember, "enumMember");
- var nameProperty = enumMember.GetType().GetProperty("Name");
- return nameProperty == null ? null : (string)nameProperty.GetValue(enumMember, null);
- }
- public System.Collections.IEnumerable GetEnumMembers(EdmType enumType)
- {
- ArgumentNotNull(enumType, "enumType");
- var membersProperty = enumType.GetType().GetProperty("Members");
- return membersProperty != null
- ? (System.Collections.IEnumerable)membersProperty.GetValue(enumType, null)
- : Enumerable.Empty<MetadataItem>();
- }
- public bool EnumIsFlags(EdmType enumType)
- {
- ArgumentNotNull(enumType, "enumType");
- var isFlagsProperty = enumType.GetType().GetProperty("IsFlags");
- return isFlagsProperty != null && (bool)isFlagsProperty.GetValue(enumType, null);
- }
- public bool IsEnumType(GlobalItem edmType)
- {
- ArgumentNotNull(edmType, "edmType");
- return edmType.GetType().Name == "EnumType";
- }
- public PrimitiveType GetEnumUnderlyingType(EdmType enumType)
- {
- ArgumentNotNull(enumType, "enumType");
- return (PrimitiveType)enumType.GetType().GetProperty("UnderlyingType").GetValue(enumType, null);
- }
- public string CreateLiteral(object value)
- {
- if (value == null || value.GetType() != typeof(TimeSpan))
- {
- return _code.CreateLiteral(value);
- }
- return string.Format(CultureInfo.InvariantCulture, "new TimeSpan({0})", ((TimeSpan)value).Ticks);
- }
- public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable<string> types, string sourceFile)
- {
- ArgumentNotNull(types, "types");
- ArgumentNotNull(sourceFile, "sourceFile");
- var hash = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
- if (types.Any(item => !hash.Add(item)))
- {
- _errors.Add(
- new CompilerError(sourceFile, -1, -1, "6023",
- String.Format(CultureInfo.CurrentCulture, GetResourceString("Template_CaseInsensitiveTypeConflict"))));
- return false;
- }
- return true;
- }
- public IEnumerable<SimpleType> GetEnumItemsToGenerate(IEnumerable<GlobalItem> itemCollection)
- {
- return GetItemsToGenerate<SimpleType>(itemCollection)
- .Where(e => IsEnumType(e));
- }
- public IEnumerable<T> GetItemsToGenerate<T>(IEnumerable<GlobalItem> itemCollection) where T: EdmType
- {
- return itemCollection
- .OfType<T>()
- .Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName))
- .OrderBy(i => i.Name);
- }
- public IEnumerable<string> GetAllGlobalItems(IEnumerable<GlobalItem> itemCollection)
- {
- return itemCollection
- .Where(i => i is EntityType || i is ComplexType || i is EntityContainer || IsEnumType(i))
- .Select(g => GetGlobalItemName(g));
- }
- public string GetGlobalItemName(GlobalItem item)
- {
- if (item is EdmType)
- {
- return ((EdmType)item).Name;
- }
- else
- {
- return ((EntityContainer)item).Name;
- }
- }
- public IEnumerable<EdmProperty> GetSimpleProperties(EntityType type)
- {
- return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type);
- }
- public IEnumerable<EdmProperty> GetSimpleProperties(ComplexType type)
- {
- return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type);
- }
- public IEnumerable<EdmProperty> GetComplexProperties(EntityType type)
- {
- return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type);
- }
- public IEnumerable<EdmProperty> GetComplexProperties(ComplexType type)
- {
- return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type);
- }
- public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(EntityType type)
- {
- return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null);
- }
- public IEnumerable<EdmProperty> GetPropertiesWithDefaultValues(ComplexType type)
- {
- return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null);
- }
- public IEnumerable<NavigationProperty> GetNavigationProperties(EntityType type)
- {
- return type.NavigationProperties.Where(np => np.DeclaringType == type);
- }
- public IEnumerable<NavigationProperty> GetCollectionNavigationProperties(EntityType type)
- {
- return type.NavigationProperties.Where(np => np.DeclaringType == type && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many);
- }
- public FunctionParameter GetReturnParameter(EdmFunction edmFunction)
- {
- ArgumentNotNull(edmFunction, "edmFunction");
- var returnParamsProperty = edmFunction.GetType().GetProperty("ReturnParameters");
- return returnParamsProperty == null
- ? edmFunction.ReturnParameter
- : ((IEnumerable<FunctionParameter>)returnParamsProperty.GetValue(edmFunction, null)).FirstOrDefault();
- }
- public bool IsComposable(EdmFunction edmFunction)
- {
- ArgumentNotNull(edmFunction, "edmFunction");
- var isComposableProperty = edmFunction.GetType().GetProperty("IsComposableAttribute");
- return isComposableProperty != null && (bool)isComposableProperty.GetValue(edmFunction, null);
- }
- public IEnumerable<FunctionImportParameter> GetParameters(EdmFunction edmFunction)
- {
- return FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef);
- }
- public TypeUsage GetReturnType(EdmFunction edmFunction)
- {
- var returnParam = GetReturnParameter(edmFunction);
- return returnParam == null ? null : _ef.GetElementType(returnParam.TypeUsage);
- }
- public bool GenerateMergeOptionFunction(EdmFunction edmFunction, bool includeMergeOption)
- {
- var returnType = GetReturnType(edmFunction);
- return !includeMergeOption && returnType != null && returnType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType;
- }
- }
- public class EdmMetadataLoader
- {
- private readonly IDynamicHost _host;
- private readonly System.Collections.IList _errors;
- public EdmMetadataLoader(IDynamicHost host, System.Collections.IList errors)
- {
- ArgumentNotNull(host, "host");
- ArgumentNotNull(errors, "errors");
- _host = host;
- _errors = errors;
- }
- public IEnumerable<GlobalItem> CreateEdmItemCollection(string sourcePath)
- {
- ArgumentNotNull(sourcePath, "sourcePath");
- if (!ValidateInputPath(sourcePath))
- {
- return new EdmItemCollection();
- }
- var schemaElement = LoadRootElement(_host.ResolvePath(sourcePath));
- if (schemaElement != null)
- {
- using (var reader = schemaElement.CreateReader())
- {
- IList<EdmSchemaError> errors;
- var itemCollection = MetadataItemCollectionFactory.CreateEdmItemCollection(new[] { reader }, out errors);
- ProcessErrors(errors, sourcePath);
- return itemCollection;
- }
- }
- return new EdmItemCollection();
- }
- public string GetModelNamespace(string sourcePath)
- {
- ArgumentNotNull(sourcePath, "sourcePath");
- if (!ValidateInputPath(sourcePath))
- {
- return string.Empty;
- }
- var model = LoadRootElement(_host.ResolvePath(sourcePath));
- if (model == null)
- {
- return string.Empty;
- }
- var attribute = model.Attribute("Namespace");
- return attribute != null ? attribute.Value : "";
- }
- private bool ValidateInputPath(string sourcePath)
- {
- if (sourcePath == "$" + "edmxInputFile" + "$")
- {
- _errors.Add(
- new CompilerError(_host.TemplateFile ?? sourcePath, 0, 0, string.Empty,
- GetResourceString("Template_ReplaceVsItemTemplateToken")));
- return false;
- }
- return true;
- }
- public XElement LoadRootElement(string sourcePath)
- {
- ArgumentNotNull(sourcePath, "sourcePath");
- var root = XElement.Load(sourcePath, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo);
- return root.Elements()
- .Where(e => e.Name.LocalName == "Runtime")
- .Elements()
- .Where(e => e.Name.LocalName == "ConceptualModels")
- .Elements()
- .Where(e => e.Name.LocalName == "Schema")
- .FirstOrDefault()
- ?? root;
- }
- private void ProcessErrors(IEnumerable<EdmSchemaError> errors, string sourceFilePath)
- {
- foreach (var error in errors)
- {
- _errors.Add(
- new CompilerError(
- error.SchemaLocation ?? sourceFilePath,
- error.Line,
- error.Column,
- error.ErrorCode.ToString(CultureInfo.InvariantCulture),
- error.Message)
- {
- IsWarning = error.Severity == EdmSchemaErrorSeverity.Warning
- });
- }
- }
- public bool IsLazyLoadingEnabled(EntityContainer container)
- {
- string lazyLoadingAttributeValue;
- var lazyLoadingAttributeName = MetadataConstants.EDM_ANNOTATION_09_02 + ":LazyLoadingEnabled";
- bool isLazyLoading;
- return !MetadataTools.TryGetStringMetadataPropertySetting(container, lazyLoadingAttributeName, out lazyLoadingAttributeValue)
- || !bool.TryParse(lazyLoadingAttributeValue, out isLazyLoading)
- || isLazyLoading;
- }
- }
- public static void ArgumentNotNull<T>(T arg, string name) where T : class
- {
- if (arg == null)
- {
- throw new ArgumentNullException(name);
- }
- }
- private static readonly Lazy<System.Resources.ResourceManager> ResourceManager =
- new Lazy<System.Resources.ResourceManager>(
- () => new System.Resources.ResourceManager("System.Data.Entity.Design", typeof(MetadataItemCollectionFactory).Assembly), isThreadSafe: true);
- public static string GetResourceString(string resourceName)
- {
- ArgumentNotNull(resourceName, "resourceName");
- return ResourceManager.Value.GetString(resourceName, null);
- }
- #>
Advertisement
Add Comment
Please, Sign In to add comment