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); }
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(); } }
/// <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); }
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); }