public bool Validate()
        {
            if (String.IsNullOrEmpty(_fileName))
            {
                return(false);
            }

            _fileName = System.IO.Path.GetFullPath(_fileName);
            if (!System.IO.File.Exists(_fileName))
            {
                return(false);
            }

            if (!System.IO.Path.HasExtension(_fileName) || !EdmxExtension.Equals(System.IO.Path.GetExtension(_fileName), StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            Edmx edmx = null;

            try {
                edmx = Edmx.Load(_fileName);
            } catch (Exception) {}

            return(edmx != null);
        }
Exemplo n.º 2
0
        private static void CreateEdmx()
        {
            ContentType.TypeSystemRestarted -= new EventHandler(ContentType_TypeSystemRestarted);
            ContentType.TypeSystemRestarted += new EventHandler(ContentType_TypeSystemRestarted);

            var context = new SchemaGenerationContext();

            CreateEntityTypes(context);
            _edmx = new Edmx
            {
                DataServices = new DataServices
                {
                    DataServiceVersion = MetaGenerator.dataServiceVersion,
                    Schemas            = new[] { new Schema
                                                 {
                                                     EntityTypes     = context.EntityTypes,
                                                     ComplexTypes    = context.ComplexTypes,
                                                     EnumTypes       = context.EnumTypes,
                                                     Associations    = context.Associations,
                                                     EntityContainer = CreateEntityContainer(context)
                                                 } }
                }
            };

            var writer = new StringWriter();

            _edmx.WriteXml(writer);
            _edmxXml = writer.GetStringBuilder().ToString();

            writer = new StringWriter();
            _edmx.WriteJson(writer);
            _edmxJson = writer.GetStringBuilder().ToString();
        }
Exemplo n.º 3
0
        public TiraggoEntityInfo(Edmx edm, string fullName)
        {
            edmx = edm;

            Mapping = edmx.Runtime.Mappings.Mapping.EntityContainerMapping.EntitySetMappings
                .Where(m => m.EntityTypeMapping.TypeName == fullName).Select(m => m).Single();

            string conceptualName = Mapping.EntityTypeMapping.TypeName.Replace(edm.Runtime.ConceptualModels.Schema.Namespace + ".", "");

            StorageInfo = edmx.Runtime.StorageModels.Schema.EntityContainer.EntitySets
                .Where(s => s.Name == Mapping.EntityTypeMapping.MappingFragment.StoreEntitySet).Single();

            ConceptualModel = edmx.Runtime.ConceptualModels.Schema.EntityTypes
                .Where(c => c is tgConceptualEntityType).Select(c => c as tgConceptualEntityType).ToList<tgConceptualEntityType>()
                .Where(c => c.Name == conceptualName).Single();

            ColumnMappings = Mapping.EntityTypeMapping.MappingFragment.ScalarProperties.ToDictionary(p => p.Name, p => p.ColumnName);

            ColumnCLR = ConceptualModel.Properties.ToDictionary(p => p.Name, p => p);

            tgEntityType sql = edm.Runtime.StorageModels.Schema.EntityTypes.Where(e => e.Name == Mapping.EntityTypeMapping.MappingFragment.StoreEntitySet).Single();

            ColumnSQL = sql.Properties.ToDictionary(e => e.Name, e => e);

            PrimaryKeys = new Dictionary<string, string>();
            foreach (tgPropertyRef key in ConceptualModel.Key)
            {
                PrimaryKeys[key.Name] = key.Name;
            }
        }
        public void Load()
        {
            if (!Validate())
            {
                return;
            }

            var edmx = Edmx.Load(_fileName);

            var conceptualNamespace = edmx.GetItems <ConceptualSchema>().First().Namespace;

            EntityNamespace  = GetDesignerProperty(edmx, EdmxConstants.EntityNamespace) ?? conceptualNamespace;
            ContextNamespace = GetDesignerProperty(edmx, EdmxConstants.ContextNamespace) ?? EntityNamespace;

            DataContextName    = edmx.GetItems <EntityContainer>().First().Name;
            LazyLoadingEnabled = edmx.GetItems <EntityContainer>().First().LazyLoadingEnabled ?? false;

            CreateEntityTypes(edmx, conceptualNamespace);
            CreateEntityFunctions(edmx, conceptualNamespace);
            CreateComplexTypes(edmx, conceptualNamespace);

            foreach (var entity in EntityStore.Instance.EntityCollection.Values)
            {
                entity.Initialize();
            }

            foreach (var entity in EntityStore.Instance.EntityCollection.Values)
            {
                entity.ValidateAllMembers();
            }
        }
Exemplo n.º 5
0
        private static Edmx CreateEdmx()
        {
            var context = new SchemaGenerationContext();

            context.Flattening = false;
            CreateEntityTypes(context);
            var edmx = new Edmx
            {
                DataServices = new DataServices
                {
                    DataServiceVersion = MetaGenerator.dataServiceVersion,
                    Schemas            = new[]
                    {
                        new Metadata.Schema
                        {
                            EntityTypes     = context.EntityTypes,
                            ComplexTypes    = context.ComplexTypes,
                            EnumTypes       = context.EnumTypes,
                            Associations    = context.Associations,
                            EntityContainer = CreateEntityContainer(context)
                        }
                    }
                }
            };

            return(edmx);
        }
Exemplo n.º 6
0
 public static List <NavigationProperty> GetNavigationProperties(this Edmx edmx, string entityName)
 {
     if (edmx.GetEntityType(entityName).NavigationProperties.Count > 0)
     {
         return(edmx.GetEntityType(entityName).NavigationProperties.ToList());
     }
     return(new List <NavigationProperty>());
 }
Exemplo n.º 7
0
        public EdmxWrapper(string fullFileName)
        {
            XmlSerializer deserializer = new XmlSerializer(typeof(Edmx));
            TextReader    reader       = new StreamReader(fullFileName);
            object        obj          = deserializer.Deserialize(reader);

            this.objEdmx = (Edmx)obj;
            reader.Close();
        }
        private static string GetDesignerProperty(Edmx edmx, string key)
        {
            var hasDesignerProperties = edmx.Designers != null && edmx.Designers.First().Options != null && edmx.Designers.First().Options.DesignerInfoPropertySet != null && edmx.Designers.First().Options.DesignerInfoPropertySet.DesignerProperties != null;

            if (hasDesignerProperties && edmx.Designers.First().Options.DesignerInfoPropertySet.DesignerProperties.Count(p => p.Name.Equals(key)) > 0)
            {
                return(edmx.Designers.First().Options.DesignerInfoPropertySet.DesignerProperties.Where(p => p.Name.Equals(key)).First().Value);
            }

            return(null);
        }
Exemplo n.º 9
0
        /// <inheritdoc />
        protected override async Task WriteMetadataAsync(HttpContext httpContext, Edmx edmx)
        {
            string result;

            using (var writer = new StringWriter())
            {
                edmx.WriteXml(writer);
                result = writer.GetStringBuilder().ToString();
            }
            await WriteRawAsync(result, httpContext).ConfigureAwait(false);
        }
Exemplo n.º 10
0
        /// <inheritdoc />
        protected override async Task WriteMetadataAsync(HttpContext httpContext, Edmx edmx)
        {
            var requestedModule = httpContext.Request.Query["module"].ToString().ToLowerInvariant();

            if (string.IsNullOrEmpty(requestedModule))
            {
                requestedModule = "classes";
            }

            var schema0 = new Schema(TypescriptGenerationContext.DisabledContentTypeNames);
            var context = new TypescriptGenerationContext();
            var schema1 = new TypescriptTypeCollectorVisitor(context).Visit(schema0);

            var writer = new StringWriter();

            switch (requestedModule)
            {
            case "enums":
                new TypescriptEnumsVisitor(context, writer).Visit(schema1);
                break;

            case "complextypes":
                new TypescriptComplexTypesVisitor(context, writer).Visit(schema1);
                break;

            case "contenttypes":
                new TypescriptClassesVisitor(context, writer).Visit(schema1);
                break;

            case "resources":
                ResourceWriter.WriteResourceClasses(writer);
                break;

            case "schemas":
                new TypescriptCtdVisitor(context, writer).Visit(schema1);
                break;

            case "fieldsettings":
                new TypescriptFieldSettingsVisitor(context, writer).Visit(schema1);
                break;

            default:
                throw new InvalidOperationException("Unknown module name: " + requestedModule
                                                    + ". Valid names: enums, complextypes, contenttypes, resources, schemas, fieldsettings.");
            }

            await httpContext.Response.WriteAsync(writer.GetStringBuilder().ToString());
        }
Exemplo n.º 11
0
        private void DoBulkInsert(DbContext dbContext, IEnumerable <object> objectsToInsert)
        {
            string connectionString = dbContext.Database.Connection.ConnectionString;

            edmx      = dbContext.GetEdmxHelper();
            schemaLib = new Schema(connectionString);

            connection = new SqlCeConnection(connectionString);

            commandIdentity             = connection.CreateCommand();
            commandIdentity.CommandType = System.Data.CommandType.Text;
            commandIdentity.CommandText = "SELECT @@IDENTITY";

            connection.Open();
            DoBulkInsert(dbContext, null, string.Empty, objectsToInsert);
            connection.Close();
        }
Exemplo n.º 12
0
        public static List <NavigationProperty> GetListProperties(this Edmx edmx, Type entityClrType)
        {
            List <NavigationProperty> properties = new List <NavigationProperty>();

            string entityName = entityClrType.Name;

            foreach (NavigationProperty navigationProperty in edmx.GetNavigationProperties(entityName))
            {
                PropertyInfo propertyInfo = entityClrType.GetProperty(navigationProperty.Name);
                if (EFLibrary.Reflection.IsCollection(propertyInfo))
                {
                    properties.Add(navigationProperty);
                }
            }

            return(properties);
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            try
            {
                var edmx = Edmx.Open("TestData/Test.edmx");
                var tableConfigurator = new Modeler(edmx.Runtime.StorageModels.Schema, "Test.EF", "TestEntities");

                foreach (var dataSetModel in tableConfigurator.DataSetModels)
                {
                    dataSetModel.WriteFiles("Models");
                }
            }
            catch (Exception e)
            {
                Debugger.Break();
            }
        }
Exemplo n.º 14
0
        public static EndProperty GetParentChildRelationEndProperty(this Edmx edmx, string parentEntityName, string childPropertyName)
        {
            NavigationProperty navigationProperty = edmx.GetNavigationProperty(parentEntityName, childPropertyName);
            string             relationship       = GetAdjustedText(navigationProperty.Relationship);

            string fromRole = navigationProperty.FromRole;
            string toRole   = navigationProperty.ToRole;

            LinqToEdmx.Model.Conceptual.Association association = edmx.GetConceptualAssociation(relationship);

            LinqToEdmx.Model.Conceptual.AssociationEnd fromAssociation = edmx.GetConceptualAssociationEnd(relationship, fromRole);
            LinqToEdmx.Model.Conceptual.AssociationEnd toAssociation   = edmx.GetConceptualAssociationEnd(relationship, toRole);

            string childEntityName = GetAdjustedText(toAssociation.Type);
            AssociationSetMapping entityTypesMappingAssociation = edmx.GetMappingAssociationSet(childEntityName, relationship);

            return(entityTypesMappingAssociation.EndProperties.Where(e => e.Name == fromRole).Single());
        }
Exemplo n.º 15
0
        private static void CreateComplexTypes(Edmx edmx, string conceptualNamespace)
        {
            // First loop through the EntityTypes and populate the EntityCollection with the Entity / Columns.
            foreach (var entity in edmx.GetItems <ComplexType>())
            {
                if (entity == null)
                {
                    continue;
                }

                if (Configuration.Instance.ExcludeRegexIsMatch(entity.Name))
                {
                    Trace.WriteLine(String.Format("Skipping EntityType: '{0}', the EntityType was excluded!", entity.Name));

                    EntityStore.Instance.ExcludedEntityCollection.Add(entity.Name, new ComplexEntity(entity, conceptualNamespace));
                    continue;
                }

                EntityStore.Instance.EntityCollection.Add(entity.Name, new ComplexEntity(entity, conceptualNamespace));
            }
        }
Exemplo n.º 16
0
        private static void CreateEntityTypes(Edmx edmx, string conceptualNamespace)
        {
            var associations = edmx.GetItems<Association>();
            var associationSets = edmx.GetItems<EntityContainer.AssociationSetLocalType>();

            // First loop through the EntityTypes and populate the EntityCollection with the Entity / Columns.
            foreach (var entity in edmx.GetItems<EntityType>()) {
                if (entity == null)
                    continue;

                if (Configuration.Instance.ExcludeRegexIsMatch(entity.Name)) {
                    Trace.WriteLine(String.Format("Skipping EntityType: '{0}', the EntityType was excluded!", entity.Name));

                    EntityStore.Instance.ExcludedEntityCollection.Add(entity.Name, new ConceptualEntity(entity, conceptualNamespace));
                    continue;
                }

                EntityStore.Instance.EntityCollection.Add(entity.Name, new ConceptualEntity(entity, associations, associationSets, conceptualNamespace));
            }
        }
Exemplo n.º 17
0
 public static LinqToEdmx.Model.Storage.EntityContainer GetStorageEntityContainer(this Edmx edmx)
 {
     return(edmx.GetItems <LinqToEdmx.Model.Storage.EntityContainer>().Single());
 }
Exemplo n.º 18
0
 public XRoot(Edmx root)
 {
     _xDocument = new XDocument(root.Untyped);
       _rootObject = root;
 }
Exemplo n.º 19
0
 public static Result <T> GetAs <T>(this Edmx @base) where T : Edmx =>
 @base is T target
Exemplo n.º 20
0
 public static string GetConceptualSchemaNamespace(this Edmx edmx)
 {
     return(edmx.GetItems <ConceptualSchema>().Single().Namespace);
 }
Exemplo n.º 21
0
 public static EntityType GetEntityType(this Edmx edmx, string entityName)
 {
     return(edmx.GetItems <EntityType>().Where(e => e.Name == entityName).Single());
 }
Exemplo n.º 22
0
 public static EntityTypeMapping GetEntityTypeMapping(this Edmx edmx, string entityFullName)
 {
     return(edmx.GetItems <EntityTypeMapping>().Where(e => e.TypeName == entityFullName).Single());
 }
Exemplo n.º 23
0
        public static Dictionary <string, string> GetScalarPropertiesMappingDictionary(this Edmx edmx, string entityName)
        {
            Dictionary <string, string> mappingDictionary = new Dictionary <string, string>();

            string entityFullName = edmx.GetEntityFullName(entityName);

            foreach (ScalarProperty scalarProperty in edmx.GetEntityTypeMapping(entityFullName).MappingFragments[0].ScalarProperties)
            {
                mappingDictionary.Add(scalarProperty.Name, scalarProperty.ColumnName);
            }

            return(mappingDictionary);
        }
Exemplo n.º 24
0
 private static void ContentType_TypeSystemRestarted(object sender, EventArgs e)
 {
     _edmx = null;
 }
Exemplo n.º 25
0
        public static Dictionary <string, string> GetLookupPropertiesMappingDictionary(this Edmx edmx, Type entityClrType)
        {
            string entityName = entityClrType.Name;
            Dictionary <string, string> mappingDictionary = new Dictionary <string, string>();

            foreach (NavigationProperty navigationProperty in edmx.GetLookupProperties(entityClrType))
            {
                string relationship = GetAdjustedText(navigationProperty.Relationship);

                string fromRole = navigationProperty.FromRole;
                string toRole   = navigationProperty.ToRole;

                LinqToEdmx.Model.Conceptual.Association association = edmx.GetConceptualAssociation(relationship);

                LinqToEdmx.Model.Conceptual.AssociationEnd fromAssociation = edmx.GetConceptualAssociationEnd(relationship, fromRole);
                LinqToEdmx.Model.Conceptual.AssociationEnd toAssociation   = edmx.GetConceptualAssociationEnd(relationship, toRole);

                AssociationSetMapping entityTypesMappingAssociation = edmx.GetMappingAssociationSet(entityName, relationship);
                foreach (EndProperty endProperty in entityTypesMappingAssociation.EndProperties)
                {
                    if (endProperty.Name == toRole)
                    {
                        string columnName = endProperty.ScalarProperties[0].ColumnName;
                        mappingDictionary.Add(navigationProperty.Name, columnName);
                    }
                }
            }

            return(mappingDictionary);
        }
Exemplo n.º 26
0
        public void Create(IEnumerable <IEntity> entities)
        {
            if (entities == null || entities.Count() <= 0)
            {
                throw new ArgumentException("Entity Collection cannot be empty", "entities");
            }

            XMLNamespaceFactory.Version = (byte)_settings.EntityFrameworkVersion;

            // TODO: We need to look into seeing if the following attributes are required in EF6.
            //<edmx:ConceptualModels>
            // <Schema Namespace="SQLModel" Alias="Self" annotation:UseStrongSpatialTypes="false" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns="http://schemas.microsoft.com/ado/2009/11/edm">

            try {
                //1. Load Database Object from and existing Edmx file or create a new Edmx Object.
                _edmx = File.Exists(_settings.MappingFile) ? Edmx.Load(_settings.MappingFile) : new Edmx();
            } catch (Exception ex) {
                throw new ApplicationException(String.Format("There was an error parsing your edmx file. If you are upgrading your existing templates you will need to delete your edmx file and regenerate. Please contact support for more information. Exception: {0}", ex.Message), ex);
            }

            bool temp;

            if (bool.TryParse(GetDesignerProperty("IncludeForeignKeysInModel"), out temp))
            {
                _includeForeignKeysInModel = temp;
            }

            //<DesignerProperty Name="EnablePluralization" Value="False" />
            //<DesignerProperty Name="CodeGenerationStrategy" Value="None" />

            foreach (var entity in entities)
            {
                if (!entity.HasKey)
                {
                    var message = String.Format("warning 6013: The table/view '{0}' does not have a primary key defined and no valid primary key could be inferred. This table/view has been excluded. To use the entity, you will need to review your schema, add the correct keys, and regenerate it.", entity.EntityKeyName);
                    Debug.WriteLine(message);
                    Trace.WriteLine(message);
                }
                else if (entity is CommandEntity && IsValidFunction(entity as CommandEntity))
                {
                    var message = String.Format("warning 6005: The function '{0}' has a parameter that has a data type (E.G., 'sql_variant') which is not supported. The function was excluded.", entity.EntityKeyName);
                    Debug.WriteLine(message);
                    Trace.WriteLine(message);
                }
            }

            entities = entities.Where(e => e.HasKey || (e is CommandEntity && IsValidFunction(e as CommandEntity)));

            //2. Sync and create the mapping models.
            //   This also builds up a list of renamed column names that we need to keep track of.
            MergeMappingModel(entities);

            foreach (IEntity entity in entities)
            {
                if (entity is TableEnumEntity)
                {
                    Debug.WriteLine("Getting Enum Table: {0}", entity.EntityKeyName);
                    //GetEnum(entity as TableEnumEntity);
                }
                else if (entity is TableEntity)
                {
                    Debug.WriteLine("Getting Table Schema: {0}", entity.EntityKeyName);
                    GetEntity(entity as TableEntity);
                }
                else if (Configuration.Instance.IncludeViews && entity is ViewEntity)
                {
                    Debug.WriteLine("Getting View Schema: {0}", entity.EntityKeyName);
                    GetEntity(entity as ViewEntity);
                }
                else if (Configuration.Instance.IncludeFunctions && entity is CommandEntity)
                {
                    Debug.WriteLine("Getting Function Schema: {0}", entity.EntityKeyName);
                    GetFunctionEntity(entity as CommandEntity);
                }

                OnSchemaItemProcessed(entity.EntityKeyName);
            }

            foreach (IEntity entity in entities)
            {
                if (entity is TableEntity)
                {
                    CreateStorageAssociations(entity as TableEntity);
                    CreateConceptualAssociations(entity as TableEntity);
                }
            }

            // validate Edmx File
            Validate();
            UpdateDesignerProperites();

            _edmx.Save(_settings.MappingFile);
        }
Exemplo n.º 27
0
        public void Create(IEnumerable<IEntity> entities)
        {
            if (entities == null || entities.Count() <= 0)
                throw new ArgumentException("Entity Collection cannot be empty", "entities");

            XMLNamespaceFactory.Version = (byte)_settings.EntityFrameworkVersion;

            // TODO: We need to look into seeing if the following attributes are required in EF6.
            //<edmx:ConceptualModels>
            // <Schema Namespace="SQLModel" Alias="Self" annotation:UseStrongSpatialTypes="false" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns="http://schemas.microsoft.com/ado/2009/11/edm">

            try {
                //1. Load Database Object from and existing Edmx file or create a new Edmx Object.
                _edmx = File.Exists(_settings.MappingFile) ? Edmx.Load(_settings.MappingFile) : new Edmx();
            } catch (Exception ex) {
                throw new ApplicationException(String.Format("There was an error parsing your edmx file. If you are upgrading your existing templates you will need to delete your edmx file and regenerate. Please contact support for more information. Exception: {0}", ex.Message), ex);
            }

            bool temp;
            if (bool.TryParse(GetDesignerProperty("IncludeForeignKeysInModel"), out temp))
                _includeForeignKeysInModel = temp;

            //<DesignerProperty Name="EnablePluralization" Value="False" />
            //<DesignerProperty Name="CodeGenerationStrategy" Value="None" />

            foreach (var entity in entities) {
                if (!entity.HasKey) {
                    var message = String.Format("warning 6013: The table/view '{0}' does not have a primary key defined and no valid primary key could be inferred. This table/view has been excluded. To use the entity, you will need to review your schema, add the correct keys, and regenerate it.", entity.EntityKeyName);
                    Debug.WriteLine(message);
                    Trace.WriteLine(message);
                } else if (entity is CommandEntity && IsValidFunction(entity as CommandEntity)) {
                    var message = String.Format("warning 6005: The function '{0}' has a parameter that has a data type (E.G., 'sql_variant') which is not supported. The function was excluded.", entity.EntityKeyName);
                    Debug.WriteLine(message);
                    Trace.WriteLine(message);
                }
            }

            entities = entities.Where(e => e.HasKey || (e is CommandEntity && IsValidFunction(e as CommandEntity)));

            //2. Sync and create the mapping models.
            //   This also builds up a list of renamed column names that we need to keep track of.
            MergeMappingModel(entities);

            foreach (IEntity entity in entities) {
                if (entity is TableEnumEntity) {
                    Debug.WriteLine("Getting Enum Table: {0}", entity.EntityKeyName);
                    //GetEnum(entity as TableEnumEntity);
                } else if (entity is TableEntity) {
                    Debug.WriteLine("Getting Table Schema: {0}", entity.EntityKeyName);
                    GetEntity(entity as TableEntity);
                } else if (Configuration.Instance.IncludeViews && entity is ViewEntity) {
                    Debug.WriteLine("Getting View Schema: {0}", entity.EntityKeyName);
                    GetEntity(entity as ViewEntity);
                } else if (Configuration.Instance.IncludeFunctions && entity is CommandEntity) {
                    Debug.WriteLine("Getting Function Schema: {0}", entity.EntityKeyName);
                    GetFunctionEntity(entity as CommandEntity);
                }

                OnSchemaItemProcessed(entity.EntityKeyName);
            }

            foreach (IEntity entity in entities) {
                if (entity is TableEntity) {
                    CreateStorageAssociations(entity as TableEntity);
                    CreateConceptualAssociations(entity as TableEntity);
                }
            }

            // validate Edmx File
            Validate();
            UpdateDesignerProperites();

            _edmx.Save(_settings.MappingFile);
        }
Exemplo n.º 28
0
        private static string GetDesignerProperty(Edmx edmx, string key)
        {
            var hasDesignerProperties = edmx.Designers != null && edmx.Designers.First().Options != null && edmx.Designers.First().Options.DesignerInfoPropertySet != null && edmx.Designers.First().Options.DesignerInfoPropertySet.DesignerProperties != null;

            if (hasDesignerProperties && edmx.Designers.First().Options.DesignerInfoPropertySet.DesignerProperties.Count(p => p.Name.Equals(key)) > 0)
                return edmx.Designers.First().Options.DesignerInfoPropertySet.DesignerProperties.Where(p => p.Name.Equals(key)).First().Value;

            return null;
        }
Exemplo n.º 29
0
 public XRootNamespace(Edmx root)
 {
     _doc = new XDocument(root.Untyped);
       _rootObject = root;
 }
Exemplo n.º 30
0
 public static EntityKeyElement GetEntityKey(this Edmx edmx, string entityName)
 {
     return(edmx.GetEntityType(entityName).Key);
 }
Exemplo n.º 31
0
 public static string GetEntityKeyPropertyName(this Edmx edmx, string entityName)
 {
     return(edmx.GetEntityKey(entityName).PropertyRefs.Single().Name);
 }
Exemplo n.º 32
0
 /// <summary>This method is not supported in this writer.</summary>
 protected override Task WriteMetadataAsync(HttpContext httpContext, Edmx edmx)
 {
     throw new SnNotSupportedException("Table writer does not support metadata writing.");
 }
Exemplo n.º 33
0
 public XRoot(Edmx root)
 {
     _xDocument  = new XDocument(root.Untyped);
     _rootObject = root;
 }
Exemplo n.º 34
0
        /// <summary>
        /// Import data structure.
        /// </summary>
        /// <param name="options">
        /// The options.
        /// </param>
        /// <returns>
        /// The <see cref="DatabaseModel"/>.
        /// </returns>
        public DatabaseModel Import(object options)
        {
            Logger.Trace("Started Import()");

            DatabaseModel     result     = new DatabaseModel();
            FileSourceOptions fileOption = options as FileSourceOptions;

            var edmx             = Edmx.Load(fileOption.Path);
            var entityTableNames = new HashSet <string>(
                edmx.Runtime.ConceptualModels.Schema.EntityTypes.Select(tbl => tbl.Name.ToUpper()));

            foreach (var table in edmx.Runtime.ConceptualModels.Schema.EntityTypes)
            {
                var tbl = new Table
                {
                    TableName  = table.Name,
                    SchemaName = new TiraggoEntityInfo(
                        edmx,
                        $"{edmx.Runtime.ConceptualModels.Schema.Namespace}.{table.Name}")
                                 .StorageInfo.Schema
                };

                result.Tables.Add(tbl);

                foreach (var col in table.Properties)
                {
                    var column = new Column
                    {
                        ColumnName     = col.Name,
                        DomainDataType = this.MapDatabaseType(col.Type, null),
                        IsPrimaryKey   = table.Key.Any(pk => pk.Name == col.Name),
                        IsRequired     =
                            (col.NullableSpecified && !col.Nullable) ||
                            table.Key.Any(pk => pk.Name == col.Name),
                        ColumnOrder = table.Properties.ToList().IndexOf(col) + 1,
                        Precision   = (col.Precision > 0 && col.Scale > 0) ? col.Precision : 0,
                        Scale       = (col.Precision > 0 && col.Scale > 0) ? col.Scale : 0,
                        Length      = string.IsNullOrEmpty(col.MaxLength)
                                                      ? 0
                                                      : Convert.ToInt32(col.MaxLength)
                    };

                    if (column.IsPrimaryKey)
                    {
                        tbl.DatabaseGeneratedKeyType = this.MapDatabaseGeneratedKey(col.StoreGeneratedPattern);
                    }

                    tbl.Columns.Add(column);
                }

                // var relationships = edmx.Runtime.StorageModels.Schemas.Associations.Where(ass => (ass.ReferentialConstraint.Dependent.Role == table.Name || ass.ReferentialConstraint.Principal.Role == table.Name) &&
                // (entityTableNames.Contains(ass.ReferentialConstraint.Dependent.Role.ToUpper()) &&
                // entityTableNames.Contains(ass.ReferentialConstraint.Principal.Role.ToUpper())));

                // Todo: Work in progress
                var relationships = edmx.Runtime.StorageModels.Schema.Associations.Where(
                    ass => (ass.ReferentialConstraint.Dependent.Role == table.Name ||
                            ass.ReferentialConstraint.Principal.Role == table.Name) &&
                    entityTableNames.Contains(ass.ReferentialConstraint.Principal.Role.ToUpper()));

                foreach (var rel in relationships)
                {
                    var ass = new Relationship
                    {
                        ReferencedTableName =
                            (rel.ReferentialConstraint.Dependent.Role == table.Name)
                                              ? rel.ReferentialConstraint.Principal.Role
                                              : rel.ReferentialConstraint.Dependent.Role,
                        ColumnName =
                            (rel.ReferentialConstraint.Dependent.Role == table.Name)
                                              ? rel.ReferentialConstraint.Dependent.PropertyRef.Name
                                              : rel.ReferentialConstraint.Principal.PropertyRef.Name,
                        ReferencedColumnName =
                            (rel.ReferentialConstraint.Principal.Role == table.Name)
                                              ? rel.ReferentialConstraint.Dependent.PropertyRef.Name
                                              : rel.ReferentialConstraint.Principal.PropertyRef.Name,
                        DependencyRelationShip =
                            (rel.ReferentialConstraint.Dependent.Role == table.Name)
                                              ? RelationshipType.ForeignKey
                                              : RelationshipType.ForeignKeyChild,
                        RelationshipName = rel.Name,

                        SchemaName = new TiraggoEntityInfo(
                            edmx,
                            $"{edmx.Runtime.ConceptualModels.Schema.Namespace}.{table.Name}")
                                     .StorageInfo.Schema
                    };

                    if (rel.Ends.Count() != 2)
                    {
                        throw new Exception("Error in association multiplicity");
                    }

                    var tblMp    = rel.Ends.First(o => o.Role == table.Name);
                    var refTblMp = rel.Ends.First(o => o.Role == ass.ReferencedTableName);

                    ass.Multiplicity           = this.MapMultiplicity(tblMp.Multiplicity);
                    ass.ReferencedMultiplicity = this.MapMultiplicity(refTblMp.Multiplicity);


                    // check For Recursive Reference:
                    var  checker   = rel.Ends.First().Type;
                    bool isSelfRef = true;

                    foreach (var item in rel.Ends)
                    {
                        if (checker != item.Type)
                        {
                            isSelfRef = false;
                        }
                    }

                    Relationship assClone = null;
                    if (isSelfRef)
                    {
                        ass.RelatedTable        = tbl;
                        ass.ReferencedTableName = table.Name;
                        ass.Table             = tbl;
                        ass.RelationshipAlias = table.Name + "_1";

                        assClone = ass.Clone() as Relationship;
                        assClone.RelationshipAlias      = table.Name + "_2";
                        assClone.ColumnName             = ass.ReferencedColumnName;
                        assClone.ReferencedColumnName   = ass.ColumnName;
                        assClone.DependencyRelationShip = RelationshipType.ForeignKey;
                        assClone.Multiplicity           = ass.ReferencedMultiplicity;
                        assClone.ReferencedMultiplicity = ass.Multiplicity;
                    }


                    tbl.Relationships.Add(ass);
                    if (assClone != null)
                    {
                        tbl.Relationships.Add(assClone);
                    }
                }

                FormatNavigationPropertiesToBeUnique(tbl);
            }



            this.Fix(result);

            Logger.Trace("Completed Import()");
            return(result);
        }
Exemplo n.º 35
0
 /// <summary>
 /// Writes the OData service metadata to the current web-response.
 /// </summary>
 /// <param name="httpContext">The current <see cref="HttpContext"/> instance containing the current web-response.</param>
 /// <param name="edmx">Metadata that will be written.</param>
 protected abstract Task WriteMetadataAsync(HttpContext httpContext, Edmx edmx);
Exemplo n.º 36
0
 public XRootNamespace(Edmx root)
 {
     _doc        = new XDocument(root.Untyped);
     _rootObject = root;
 }