public ModelScalarType SuggestType(MetaModelBuilder metaModelBuilder) { //ModelTypeScalar scalarType = this.Type?.GetScalarType(); ModelSematicScalarType scalarType = this.SqlType.GetScalarType(); var result = new ModelScalarType { Name = scalarType.Name.GetQFullName("[", 2), ExternalName = scalarType.GetCondensed(), MaxLength = this.MaxLength, Scale = this.Scale, Precision = this.Precision, Nullable = this.Nullable, Type = scalarType.GetClrType() }; return(result); }
public override ModelSchema GetModelSchema(MetaModelBuilder metaModelBuilder, ModelErrors errors) { var result = this.ModelSchema; if (result is null) { if (this._EdmxModel != null) { var builder = new EdmxModelSchemaBuilder(); result = new ModelSchema(); builder.Build(this._EdmxModel, result, metaModelBuilder, errors); #warning result.Freeze(); this.ModelSchema = result; } } return(result); }
public void SqlRepositoryImplementation_ReadSQLSchema_Test() { var testCfg = OfaSchlupfer.TestCfg.Get(); var repSQLConnectionString = testCfg.SQLConnectionString; IServiceCollection services = new ServiceCollection(); services.AddLogging((builder) => { builder.AddDebug(); }); var serviceProvider = services.BuildServiceProvider(); var modelRoot = new ModelRoot(); var modelRepository = new ModelRepository(); modelRepository.Name = "ProjectServerSQL"; modelRoot.Repositories.Add(modelRepository); SqlRepositoryModel sqlRepository = new SqlRepositoryImplementation(); sqlRepository.ConnectionString = repSQLConnectionString; modelRepository.ReferencedRepositoryModel = sqlRepository; var errors = new ModelErrors(); MetaModelBuilder metaModelBuilder = new MetaModelBuilder(); sqlRepository.ReadSQLSchema(metaModelBuilder, errors); if (errors.HasErrors()) { output.WriteLine(errors.ToString()); } Assert.False(errors.HasErrors()); Assert.NotNull(sqlRepository.ModelSchema); Assert.True(sqlRepository.ModelSchema.ComplexTypes.Count > 0); var entitySchema = sqlRepository.ModelSchema.GetEntitySchema(); Assert.NotNull(entitySchema); { var serializeSettings = new Newtonsoft.Json.JsonSerializerSettings(); serializeSettings.TypeNameAssemblyFormatHandling = Newtonsoft.Json.TypeNameAssemblyFormatHandling.Simple; serializeSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto; var schemaAsJson = Newtonsoft.Json.JsonConvert.SerializeObject(sqlRepository.ModelSchema, Newtonsoft.Json.Formatting.Indented, serializeSettings); try { string outputPath = System.IO.Path.Combine(testCfg.SolutionFolder, @"test\temp\SqlRepositoryImplementation_ReadSQLSchema_Test_ModelSchema.json"); System.IO.File.WriteAllText(outputPath, schemaAsJson); } catch { throw; } } { var serializeSettings = new Newtonsoft.Json.JsonSerializerSettings(); serializeSettings.TypeNameAssemblyFormatHandling = Newtonsoft.Json.TypeNameAssemblyFormatHandling.Simple; serializeSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto; var schemaAsJson = Newtonsoft.Json.JsonConvert.SerializeObject(entitySchema, Newtonsoft.Json.Formatting.Indented, serializeSettings); try { string outputPath = System.IO.Path.Combine(testCfg.SolutionFolder, @"test\temp\SqlRepositoryImplementation_ReadSQLSchema_Test_EntitySchema.json"); System.IO.File.WriteAllText(outputPath, schemaAsJson); } catch { throw; } } }
public void Mapping_OData_SQL_ProjectOnlinemetadata_Test() { var testCfg = OfaSchlupfer.TestCfg.Get(); var repCSProjectServer = testCfg.ProjectServer.CreateWithSuffix("/_api/ProjectData/[en-us]"); repCSProjectServer.AuthenticationMode = "SPOIDCRL"; var srcPath = System.IO.Path.Combine(testCfg.SolutionFolder, @"test\ProjectOnlinemetadata.xml"); IServiceCollection services = new ServiceCollection(); services.AddLogging((builder) => { builder.AddDebug(); }); services.AddOfaSchlupferModel(); services.AddOfaSchlupferEntity(); services.AddOfaSchlupferODataRepository(); services.AddSqlRepository(); services.AddServiceClientCredentials((builder) => { }); //services.AddHttpClient((builder) => { }); var serviceProvider = services.BuildServiceProvider(); using (var scope = serviceProvider.CreateScope()) { var scopedServiceProvider = scope.ServiceProvider; var modelRoot = scopedServiceProvider.GetRequiredService <ModelRoot>(); var modelRepositorySource = modelRoot.CreateRepository("Source", "OData"); var modelDefininition = modelRepositorySource.CreateModelDefinition(null); Assert.Same(modelDefininition, modelRepositorySource.ModelDefinition); modelDefininition.MetaData = System.IO.File.ReadAllText(srcPath); var oDataRepositorySource = (ODataRepositoryImplementation)modelRepositorySource.GetReferenceRepositoryModel(); Assert.NotNull(oDataRepositorySource); Assert.Same(modelRepositorySource, oDataRepositorySource.Owner); Assert.NotNull(oDataRepositorySource.GetEdmxModel()); var modelSchemaSource = modelRepositorySource.GetModelSchema(null, null); Assert.NotNull(modelSchemaSource); EntitySchema entitySchema = modelRepositorySource.ModelSchema.GetEntitySchema(); Assert.NotNull(entitySchema); var modelRepositoryTarget = modelRoot.CreateRepository("Target", "SQL"); var sqlRepositoryTarget = (SqlRepositoryImplementation)modelRepositoryTarget.GetReferenceRepositoryModel(); sqlRepositoryTarget.ConnectionString = testCfg.SQLConnectionString; Assert.NotNull(sqlRepositoryTarget); { var metaModelBuilder = new MetaModelBuilder(); var errors = new ModelErrors(); var modelSchemaTarget = modelRepositoryTarget.GetModelSchema(metaModelBuilder, errors); Assert.NotNull(modelSchemaTarget); if (errors.HasErrors()) { this.output.WriteLine(errors.ToString()); } Assert.False(errors.HasErrors()); Assert.True(sqlRepositoryTarget.ModelDatabase.Tables.Count > 0); foreach (var table in sqlRepositoryTarget.ModelDatabase.Tables) { Assert.True(table.Columns.Count > 0); } Assert.NotNull(modelSchemaTarget); Assert.True(modelSchemaTarget.Entities.Count > 0); Assert.True(modelSchemaTarget.ComplexTypes.Count > 0); foreach (var modelEntityTarget in modelRepositoryTarget.ModelSchema.Entities) { Assert.NotNull(modelEntityTarget.EntityTypeName); Assert.NotNull(modelEntityTarget.EntityType); } foreach (var modelComplexTypesTarget in modelRepositoryTarget.ModelSchema.ComplexTypes) { if (modelComplexTypesTarget.Properties.Count == 0) { var message = $"{modelComplexTypesTarget.Name} has no properties."; this.output.WriteLine(message); Assert.Equal("Error", message); } if (modelComplexTypesTarget.Indexes.Count == 0) { var message = $"{modelComplexTypesTarget.Name} has no indexes."; this.output.WriteLine(message); Assert.Equal("Error", message); } } } { var serializeSettings = new Newtonsoft.Json.JsonSerializerSettings { TypeNameAssemblyFormatHandling = Newtonsoft.Json.TypeNameAssemblyFormatHandling.Simple, TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects }; serializeSettings.Converters.Add(new OfaSchlupfer.MSSQLReflection.Model.SqlNameJsonConverter()); //serializeSettings.Converters.Add(new OfaSchlupfer.MSSQLReflection.Model.ModelSqlTableJsonConverter()); //serializeSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); //serializeSettings.TraceWriter = new XunitTraceWriter(output); try { var schemaAsJson = Newtonsoft.Json.JsonConvert.SerializeObject(sqlRepositoryTarget.ModelDatabase, Newtonsoft.Json.Formatting.Indented, serializeSettings); string outputPath = System.IO.Path.Combine(testCfg.SolutionFolder, @"test\temp\Mapping_OData_SQL_ProjectOnlinemetadata_Test-target-ModelDatabase-Before.json"); System.IO.File.WriteAllText(outputPath, schemaAsJson); } catch (Exception error) { this.output.WriteLine(error.ToString()); throw; } } { var mappingModelRepositorySourceTarget = modelRoot.CreateMapping("SourceTarget", modelRepositorySource, modelRepositoryTarget); var mappingModelSchema = mappingModelRepositorySourceTarget.CreateMappingModelSchema("SourceTarget", modelRepositorySource.ModelSchema, modelRepositoryTarget.ModelSchema, true, false, ""); var mappingModelBuilder = new MappingModelBuilder { MappingModelRepository = mappingModelRepositorySourceTarget }; var errors = new ModelErrors(); mappingModelBuilder.EnabledForCreatedMappings = true; mappingModelBuilder.Comment = "Mapping_OData_SQL_ProjectOnlinemetadata_Test"; mappingModelBuilder.Build(errors); if (errors.HasErrors()) { this.output.WriteLine(errors.ToString()); } Assert.False(errors.HasErrors()); foreach (var modelEntityTarget in modelRepositoryTarget.ModelSchema.Entities) { Assert.NotNull(modelEntityTarget.EntityTypeName); Assert.NotNull(modelEntityTarget.EntityType); } foreach (var modelComplexTypesTarget in modelRepositoryTarget.ModelSchema.ComplexTypes) { if (modelComplexTypesTarget.Properties.Count == 0) { var message = $"{modelComplexTypesTarget.Name} has no properties"; this.output.WriteLine(message); Assert.Equal("Error", message); } } } { #warning HEEEEEEEEEEEEEEERE var metaModelBuilder = new MetaModelBuilder(); var errors = new ModelErrors(); var sqlModelSchemaBuilder = new SqlModelSchemaBuilder(); sqlModelSchemaBuilder.BuildModelSqlDatabase( modelRepositoryTarget.ModelSchema, sqlRepositoryTarget.ModelDatabase, metaModelBuilder, errors ); if (errors.HasErrors()) { this.output.WriteLine(errors.ToString()); } Assert.False(errors.HasErrors()); } var cred = new SharePointOnlineServiceClientCredentials(repCSProjectServer, null); var oDataClient = new ODataServiceClient(new Uri(repCSProjectServer.GetUrlNormalized()), cred, null) { ModelRepository = modelRepositorySource }; var oDataRequest = oDataClient.Query("Projects"); // oDataClient.ConnectionString = repCSProjectServer; // oDataClient.SetConnectionString(repCSProjectServer, "/_api/ProjectData/[en-us]"); var srcPathData = System.IO.Path.Combine(testCfg.SolutionFolder, @"test\ProjectOnlineData-Projects.json"); var responceContentString = System.IO.File.ReadAllText(srcPathData); var operationResponse = new AzureOperationResponse <ODataRequest> { Request = new System.Net.Http.HttpRequestMessage(), Response = new System.Net.Http.HttpResponseMessage() { Content = new System.Net.Http.StringContent(responceContentString) } }; ODataDeserializtion d = new ODataDeserializtion(oDataRequest, oDataClient); var deserializeResult = d.Deserialize(responceContentString); Assert.NotNull(deserializeResult); Assert.IsType <List <IEntity> >(deserializeResult); var lstEntity = deserializeResult as List <IEntity>; Assert.Equal(60, lstEntity.Count); { var serializeSettings = new Newtonsoft.Json.JsonSerializerSettings { TypeNameAssemblyFormatHandling = Newtonsoft.Json.TypeNameAssemblyFormatHandling.Simple, TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto }; var schemaAsJson = Newtonsoft.Json.JsonConvert.SerializeObject(modelRoot, Newtonsoft.Json.Formatting.Indented, serializeSettings); try { string outputPath = System.IO.Path.Combine(testCfg.SolutionFolder, @"test\temp\Mapping_OData_SQL_ProjectOnlinemetadata_Test-root.json"); System.IO.File.WriteAllText(outputPath, schemaAsJson); } catch { throw; } } { var serializeSettings = new Newtonsoft.Json.JsonSerializerSettings { TypeNameAssemblyFormatHandling = Newtonsoft.Json.TypeNameAssemblyFormatHandling.Simple, TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects }; serializeSettings.Converters.Add(new OfaSchlupfer.MSSQLReflection.Model.SqlNameJsonConverter()); //serializeSettings.Converters.Add(new OfaSchlupfer.MSSQLReflection.Model.ModelSqlTableJsonConverter()); //serializeSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); //serializeSettings.TraceWriter = new XunitTraceWriter(output); try { var schemaAsJson = Newtonsoft.Json.JsonConvert.SerializeObject(sqlRepositoryTarget.ModelDatabase, Newtonsoft.Json.Formatting.Indented, serializeSettings); string outputPath = System.IO.Path.Combine(testCfg.SolutionFolder, @"test\temp\Mapping_OData_SQL_ProjectOnlinemetadata_Test-target-ModelDatabase-After.json"); System.IO.File.WriteAllText(outputPath, schemaAsJson); } catch (Exception error) { this.output.WriteLine(error.ToString()); throw; } } { var errors = new ModelErrors(); //sqlRepositoryTarget.UpdateTargetSchema(errors); var sqlScript = new StringBuilder(); sqlRepositoryTarget.GenerateUpdateSchemaSQL(errors, (name, sql) => { sqlScript.Append($"-- start{name}\r\n{sql}\r\nGO\r\n-- endof:{name}\r\n\r\n"); }); if (errors.HasErrors()) { this.output.WriteLine(errors.ToString()); } Assert.False(errors.HasErrors()); string outputPath = System.IO.Path.Combine(testCfg.SolutionFolder, @"test\temp\Mapping_OData_SQL_ProjectOnlinemetadata_Test.sql"); System.IO.File.WriteAllText(outputPath, sqlScript.ToString()); } } }
public void BuildAssociation(EdmxModel edmxModel, ModelSchema modelSchema, CsdlAssociationModel association, MetaModelBuilder metaModelBuilder, ModelErrors errors) { foreach (var associationEnd in association.AssociationEnd) { if (associationEnd.TypeModel is null) { if (!(associationEnd.TypeName is null)) { errors.AddErrorOrThrow($"{associationEnd.TypeName} not found.", $"{association.FullName} - {associationEnd.FullName}"); } continue; } //associationEnd.GetMultiplicity() //var roleName = associationEnd.RoleName; //associationEnd.TypeModel } var lstOneOptional = association.AssociationEnd.Where(end => end.GetMultiplicity() == MultiplicityKind.OneOptional).ToList(); var lstOne = association.AssociationEnd.Where(end => end.GetMultiplicity() == MultiplicityKind.One).ToList(); var lstMultiple = association.AssociationEnd.Where(end => end.GetMultiplicity() == MultiplicityKind.Multiple).ToList(); if ((lstOneOptional.Count == 1) && (lstMultiple.Count == 1)) { var masterEnd = lstOneOptional[0]; var foreignEnd = lstMultiple[0]; var lstMasterProperty = masterEnd.TypeModel.NavigationProperty.Where(np => np.FromRoleName == masterEnd.RoleName).ToList(); var lstForeignProperty = foreignEnd.TypeModel.NavigationProperty.Where(np => np.FromRoleName == foreignEnd.RoleName).ToList(); if ((lstMasterProperty.Count == 1) && (lstForeignProperty.Count == 1)) { //modelSchema.ComplexTypes.FindByKey2(lstMasterProperty[0]) //modelSchema.ComplexTypes.FindByKey2(lstMasterProperty[0].TypeModel.Nam) var result = metaModelBuilder.CreateModelRelation( association.Name, association.FullName, lstMasterProperty[0].ToRoleModel.TypeName, lstMasterProperty[0].Name, lstForeignProperty[0].ToRoleModel.TypeName, lstForeignProperty[0].Name ); modelSchema.Relations.Add(result); } } }
public ModelScalarType BuildScalarType(EdmxModel edmxModel, ModelSchema modelSchema, CsdlScalarTypeModel scalarTypeModel, MetaModelBuilder metaModelBuilder, ModelErrors errors) { if (string.Equals(scalarTypeModel.Namespace, "Edm", StringComparison.Ordinal)) { return(null); } // #warning BuildScalarType - when does this happen? var name = scalarTypeModel.Name; var fullName = scalarTypeModel.FullName; ModelScalarType result = new ModelScalarType { Name = name, ExternalName = fullName }; modelSchema.ScalarTypes.Add(result); return(result); }
public ModelComplexType BuildComplexTypeNavigationProperty(EdmxModel edmxModel, ModelSchema modelSchema, CsdlEntityTypeModel entityTypeModel, MetaModelBuilder metaModelBuilder, ModelErrors errors) { ModelComplexType result = null; var entityTypeModelName = entityTypeModel.Name; var entityTypeModelFullName = entityTypeModel.FullName; var lstFound = modelSchema.ComplexTypes.FindByKey2(entityTypeModelFullName ?? entityTypeModelName); if (lstFound.Count == 1) { result = lstFound[0]; } else if (lstFound.Count > 1) { errors.AddErrorOrThrow(new ModelErrorInfo($"found key {entityTypeModelFullName ?? entityTypeModelName} #{lstFound.Count} times.", entityTypeModelFullName ?? entityTypeModelName)); result = lstFound[0]; } else { result = BuildComplexType(edmxModel, modelSchema, entityTypeModel, metaModelBuilder, errors); } if (result == null) { return(null); } foreach (var navigationProperty in entityTypeModel.NavigationProperty) { if (navigationProperty.RelationshipName is null) { //navigationProperty.Name //navigationProperty.TypeModel //navigationProperty.PartnerModel throw new NotImplementedException("v4 NavigationProperty"); } else { // v3 //if (navigationProperty.FromRoleModel is null) { //} else { //} if (navigationProperty.ToRoleModel is null) { } else { var toModel = navigationProperty.ToRoleModel.TypeModel; var lstToComplexTypes = modelSchema.ComplexTypes.FindByKey2(toModel.FullName); if (lstToComplexTypes.Count == 1) { var toComplexType = lstToComplexTypes[0]; var navigationPropertyExternalName = navigationProperty.Name; #warning magic needed here var navigationPropertyName = navigationPropertyExternalName; bool isCollection = false; bool isOptional = false; switch (navigationProperty.ToRoleModel.GetMultiplicity()) { case MultiplicityKind.Unknown: break; case MultiplicityKind.OneOptional: isOptional = true; break; case MultiplicityKind.One: break; case MultiplicityKind.Multiple: isCollection = true; break; default: break; } var modelNavigationProperty = result.CreateNavigationProperty( navigationPropertyName, navigationPropertyExternalName, toComplexType, isOptional, isCollection ); } } } } /* */ return(result); }
public ModelComplexType BuildComplexType(EdmxModel edmxModel, ModelSchema modelSchema, CsdlEntityTypeModel entityTypeModel, MetaModelBuilder metaModelBuilder, ModelErrors errors) { var entityTypeModelName = entityTypeModel.Name; var entityTypeModelFullName = entityTypeModel.FullName; var lstFound = modelSchema.ComplexTypes.FindByKey2(entityTypeModelFullName ?? entityTypeModelName); if (lstFound.Count == 1) { return(lstFound[0]); } else if (lstFound.Count > 1) { errors.AddErrorOrThrow(new ModelErrorInfo($"found key {entityTypeModelFullName ?? entityTypeModelName} #{lstFound.Count} times.", entityTypeModelFullName ?? entityTypeModelName)); return(lstFound[0]); } var modelComplexType = metaModelBuilder.CreateModelComplexType( entityTypeModelName, entityTypeModelFullName, errors); if (modelComplexType.Owner == null) { modelSchema.ComplexTypes.Add(modelComplexType); } foreach (var property in entityTypeModel.Property) { ModelScalarType modelScalarType = null; ModelScalarType suggestedType = property.SuggestType(metaModelBuilder); // TODO: thinkof EdmxModelBuilder Build ScalarType //if (property.ScalarType != null) { // property.ScalarType.FullName //} modelScalarType = metaModelBuilder.CreateModelScalarType( entityTypeModelName, entityTypeModelFullName, property.Name, null, property.TypeName, suggestedType, property.MaxLength, property.FixedLength, property.Nullable, property.Precision, property.Scale, errors ); var modelProperty = metaModelBuilder.CreateModelProperty( entityTypeModelName, entityTypeModelFullName, property.Name, null, errors ); if (modelProperty.Type == null) { modelProperty.Type = modelScalarType; } if (modelProperty.Owner == null) { modelComplexType.Properties.Add(modelProperty); } } var primaryKey = entityTypeModel.Keys; if (primaryKey.Count > 0) { var modelIndex = metaModelBuilder.CreateModelIndex( entityTypeModelName, entityTypeModelFullName, "PrimaryKey", null, errors ); modelIndex.IsPrimaryKey = true; if (modelIndex.Owner == null) { modelComplexType.Indexes.Add(modelIndex); } foreach (var keyModel in entityTypeModel.Keys) { var modelIndexProperty = metaModelBuilder.CreateModelIndexProperty( entityTypeModelName, entityTypeModelFullName, modelIndex.Name, modelIndex.ExternalName, keyModel.Name, null, //keyModel.Property, errors ); if (modelIndexProperty.Owner == null) { modelIndex.Properties.Add(modelIndexProperty); } } } return(modelComplexType); }
public ModelSchema Build( EdmxModel edmxModel, ModelSchema modelSchema, MetaModelBuilder metaModelBuilder, ModelErrors errors) { if (modelSchema == null) { modelSchema = new ModelSchema(); } //if (metaMappingSchema == null) { metaMappingSchema = new MetaMappingSchema(); } if (metaModelBuilder == null) { metaModelBuilder = new MetaModelBuilder(); } if (!edmxModel.IsFrozen()) { edmxModel.AddCoreSchemaIfNeeded(errors); edmxModel.Freeze(); } var defaultEntityContainers = edmxModel.DataServices.SelectMany(_ => _.EntityContainer).Where(_ => _.IsDefaultEntityContainer).ToList(); if (defaultEntityContainers.Count != 1) { defaultEntityContainers = edmxModel.DataServices.SelectMany(_ => _.EntityContainer).ToList(); } if (defaultEntityContainers.Count != 1) { errors.AddErrorOrThrow($"DefaultEntityContainers #{defaultEntityContainers.Count} found.", "model"); return(modelSchema); } var defaultEntityContainer = defaultEntityContainers[0]; edmxModel.ResolveNames(errors); if (errors.HasErrors()) { return(modelSchema); } foreach (var dataServices in edmxModel.DataServices) { foreach (var scalarTypeModel in dataServices.ScalarTypeModel) { this.BuildScalarType(edmxModel, modelSchema, scalarTypeModel, metaModelBuilder, errors); } } foreach (var dataServices in edmxModel.DataServices) { foreach (var entityTypeModel in dataServices.EntityType) { this.BuildComplexType(edmxModel, modelSchema, entityTypeModel, metaModelBuilder, errors); } } foreach (var dataServices in edmxModel.DataServices) { foreach (var entityTypeModel in dataServices.EntityType) { this.BuildComplexTypeNavigationProperty(edmxModel, modelSchema, entityTypeModel, metaModelBuilder, errors); } } foreach (var dataServices in edmxModel.DataServices) { foreach (var association in dataServices.Association) { this.BuildAssociation(edmxModel, modelSchema, association, metaModelBuilder, errors); } } //foreach (var dataServices in edmxModel.DataServices) { // foreach (var entityContainer in dataServices.EntityContainer) { // if (entityContainer.IsDefaultEntityContainer) { continue; } // } //} foreach (var entitySet in defaultEntityContainer.EntitySet) { var entityTypeModel = entitySet.EntityTypeModel; if (entityTypeModel == null) { errors.AddErrorOrThrow("entitySet.EntityTypeModel not found", entitySet.Name); } else { var entityTypeModelName = entityTypeModel.Name; var entityTypeModelFullName = entityTypeModel.FullName; var modelComplexType = this.BuildComplexType(edmxModel, modelSchema, entityTypeModel, metaModelBuilder, errors); var entitySetName = entitySet.Name; var modelEntity = metaModelBuilder.CreateModelEntity( entitySetName, ModelEntityKind.EntitySet, errors); if (modelEntity.Owner == null) { modelSchema.Entities.Add(modelEntity); } if (modelComplexType is null) { errors.AddErrorOrThrow($"{entityTypeModelFullName ?? entityTypeModelName} not found", entitySet.Name); } else { modelEntity.EntityType = modelComplexType; } } } //foreach (var associationSet in defaultEntityContainer.AssociationSet) { // foreach (var end in associationSet.End) { // if (!(end.EntitySetModel is null)) { // var roleName = d.RoleName; // } // } //} return(modelSchema); }
public void BuildModelSqlDatabase( ModelSchema modelSchema, ModelSqlDatabase modelDatabase, MetaModelBuilder metaModelBuilder, ModelErrors errors) { foreach (var modelEntitySource in modelSchema.Entities) { var modelEntityTypeSource = modelEntitySource.EntityType; if (modelEntityTypeSource is null) { #warning SOON add error } else { var tableNameTarget = modelEntitySource.ExternalName ?? modelEntitySource.Name; var sqlTableNameTarget = SqlName.Parse(tableNameTarget, ObjectLevel.Object); var tableTarget = ModelSqlTable.Ensure(modelDatabase, sqlTableNameTarget); foreach (var property in modelEntityTypeSource.Properties) { var sqlColumnNameTarget = SqlName.Parse(property.ExternalName ?? property.Name, ObjectLevel.Object); ModelSqlColumn column = ModelSqlColumn.Ensure(tableTarget, sqlColumnNameTarget.Name); if (property.Type is ModelScalarType propertyScalarType) { var clrTypeSource = property.GetClrType(); var typeName = propertyScalarType.Name; #warning TODO SOON better Scalar Type Handling this is ugly if (!(clrTypeSource is null)) { var innerNullableClrTypeSource = ((clrTypeSource.IsValueType) ? Nullable.GetUnderlyingType(clrTypeSource) : null) ?? clrTypeSource; if (!(column.SqlType is null)) { var clrScalarTypeTarget = column.SqlType.GetScalarType()?.GetClrType(); var innerNullableClrScalarTypeTarget = ((clrScalarTypeTarget.IsValueType) ? Nullable.GetUnderlyingType(clrScalarTypeTarget) : null) ?? clrScalarTypeTarget; if (!(clrScalarTypeTarget is null) && (clrScalarTypeTarget.IsAssignableFrom(innerNullableClrScalarTypeTarget))) { // ok } else { column.SqlType = null; } } } if (column.SqlType is null) { var sqlTypeTarget = modelDatabase.Types.GetValueOrDefault(SqlName.Parse(typeName, ObjectLevel.Object)); if (!(sqlTypeTarget is null)) { column.SqlType = sqlTypeTarget; } else { if (!(clrTypeSource is null)) { var innerNullableClrTypeSource = ((clrTypeSource.IsValueType) ? Nullable.GetUnderlyingType(clrTypeSource) : null) ?? clrTypeSource; var lstTypes = new List <ModelSqlType>(); foreach (var type in modelDatabase.Types) { var clrScalarTypeTarget = type.GetScalarType()?.GetClrType(); if (clrScalarTypeTarget is null) { continue; } var innerNullableClrScalarTypeTarget = ((clrScalarTypeTarget.IsValueType) ? Nullable.GetUnderlyingType(clrScalarTypeTarget) : null) ?? clrScalarTypeTarget; if (innerNullableClrTypeSource.Equals(innerNullableClrScalarTypeTarget)) { lstTypes.Add(type); } else if (innerNullableClrTypeSource.IsAssignableFrom(innerNullableClrScalarTypeTarget)) { lstTypes.Add(type); } } if (lstTypes.Count == 1) { sqlTypeTarget = lstTypes[0]; column.SqlType = sqlTypeTarget; } else if (lstTypes.Count > 1) { sqlTypeTarget = null; if (clrTypeSource == typeof(string)) { sqlTypeTarget = modelDatabase.Types.GetValueOrDefault(SqlName.Parse("[sys].[nvarchar]", ObjectLevel.Object)); } else if (clrTypeSource == typeof(DateTime)) { sqlTypeTarget = modelDatabase.Types.GetValueOrDefault(SqlName.Parse("[sys].[datetime2]", ObjectLevel.Object)); } else if (clrTypeSource == typeof(DateTime?)) { sqlTypeTarget = modelDatabase.Types.GetValueOrDefault(SqlName.Parse("[sys].[datetime2]", ObjectLevel.Object)); } if (sqlTypeTarget is null) { sqlTypeTarget = lstTypes[0]; } column.SqlType = sqlTypeTarget; } else { errors.Add(new ModelErrorInfo($"Unknown mapping for {typeName} - {clrTypeSource}.", column.NameSql)); sqlTypeTarget = modelDatabase.Types.GetValueOrDefault(SqlName.Parse("[sys].[nvarchar]", ObjectLevel.Object)); column.SqlType = sqlTypeTarget; } } } sqlTypeTarget = column.SqlType; if (sqlTypeTarget is null) { errors.Add(new ModelErrorInfo($"column.SqlType is null.", column.NameSql)); } else { sqlTypeTarget.Nullable = propertyScalarType.Nullable.GetValueOrDefault(true); if (propertyScalarType.MaxLength.HasValue) { sqlTypeTarget.MaxLength = propertyScalarType.MaxLength; } else { //if (typeof(string).Equals(sqlTypeTarget.GetScalarType().GetClrType())) { // sqlTypeTarget.MaxLength = -1; //} } } } // if (column.SqlType is null) }
public void BuildModelSchema( ModelSqlDatabase modelDatabase, ModelSchema modelSchema, MetaModelBuilder metaModelBuilder, ModelErrors errors) { if (modelSchema == null) { modelSchema = new ModelSchema(); } if (metaModelBuilder == null) { metaModelBuilder = new MetaModelBuilder(); } // modelDatabase.Freeze(); foreach (var table in modelDatabase.Tables) { var entityTypeModelName = table.Name.GetQFullName(null, 2); var entityTypeModelFullName = table.Name.GetQFullName("[", 2); var modelComplexType = metaModelBuilder.CreateModelComplexType( entityTypeModelName, entityTypeModelFullName, errors); if (modelComplexType.Owner == null) { modelSchema.ComplexTypes.Add(modelComplexType); } foreach (var column in table.Columns) { ModelScalarType modelScalarType = null; ModelScalarType suggestedType = column.SuggestType(metaModelBuilder); modelScalarType = metaModelBuilder.CreateModelScalarType( entityTypeModelName, entityTypeModelFullName, column.Name.GetQName(), null, column.SqlType.Name.GetQFullName(), suggestedType, column.MaxLength, column.FixedLength, column.Nullable, column.Precision, column.Scale, errors ); var columnName = column.Name.GetQFullName(null, 1); var columnExternalName = column.Name.GetQFullName("[", 1); var modelProperty = metaModelBuilder.CreateModelProperty( entityTypeModelName, entityTypeModelFullName, columnName, columnExternalName, errors ); if (modelProperty.Type == null) { modelProperty.Type = modelScalarType; } if (modelProperty.Owner == null) { modelComplexType.Properties.Add(modelProperty); } } var tableIndexes = table.Indexes.ToList(); var lstPrimaryIndex = tableIndexes.Where(sqlIndex => sqlIndex.IsPrimaryKey).ToList(); var primaryIndex = lstPrimaryIndex.FirstOrDefault(); if (lstPrimaryIndex.Count == 1) { //var sqlIndex = lstPrimaryIndex[0]; // OK } else if (lstPrimaryIndex.Count > 1) { errors.AddErrorOrThrow($"More than one ({lstPrimaryIndex.Count}) primary key.", table.NameSql); } else { #warning think of no primary key } foreach (var sqlIndex in tableIndexes) { #warning have indexes a schema?? var modelIndex = metaModelBuilder.CreateModelIndex(entityTypeModelName, entityTypeModelFullName, sqlIndex.Name.Name, sqlIndex.Name.Name, errors); //modelIndex.IsPrimaryKey = sqlIndex.IsPrimaryKey; modelIndex.IsPrimaryKey = ReferenceEquals(sqlIndex, primaryIndex); modelComplexType.Indexes.Add(modelIndex); foreach (var column in sqlIndex.Columns) { var modelIndexProperty = metaModelBuilder.CreateModelIndexProperty( entityTypeModelName, entityTypeModelFullName, sqlIndex.Name.Name, sqlIndex.Name.Name, column.Name.Name, null, errors ); modelIndex.Properties.Add(modelIndexProperty); } } var entitySetName = table.Name.GetQFullName(null, 2); var modelEntity = metaModelBuilder.CreateModelEntity( entitySetName, ModelEntityKind.EntitySet, errors); if (modelEntity.Owner == null) { modelSchema.Entities.Add(modelEntity); } modelEntity.EntityType = modelComplexType; } }