public static void WriteSsdl(this StoreItemCollection storeItemCollection, XmlWriter writer, string schemaNamespaceName = null)
        {
            Debug.Assert(storeItemCollection != null, "storeItemCollection != null");
            Debug.Assert(writer != null, "writer != null");

            // In the StoreItemCollection all non-primitive types (either EntityType or AssociationType) are in the same namespace.
            // If there is any EntityType we should use the namespace of this type and it should win over the namespace defined by the user
            // otherwise we could "move" all the types to the namespace defined by the user since in the SsdlWriter we use the namespace
            // alias when writing the type (note that if we used the namespace instead of alias we could create an invalid Ssdl since
            // the types would be in a different (and undefined) namespace then the one written on the Schema element).
            // To infer the namespace we use EntitType because you any other type with a namespace (e.g. EntitySet, AssociationType etc.)
            // refer to an entity type. If there are no entity types we will use the namespace name provided by the user or - if it is null
            // or empty - we will an arbitrary one (at this point the schema name does not really matter since the collection
            // does not have any type that would use it)
            var entityType = storeItemCollection.GetItems <EntityType>().FirstOrDefault();

            if (entityType != null)
            {
                schemaNamespaceName = entityType.NamespaceName;
            }
            else if (string.IsNullOrWhiteSpace(schemaNamespaceName))
            {
                schemaNamespaceName = "Model.Store";
            }

            new SsdlSerializer()
            .Serialize(
                storeItemCollection.ToEdmModel(),
                schemaNamespaceName,
                storeItemCollection.ProviderInvariantName,
                storeItemCollection.ProviderManifestToken,
                writer,
                serializeDefaultNullability: false);
        }
示例#2
0
        internal static string CreateObjectsScript(
            StoreItemCollection itemCollection,
            bool createSchemas)
        {
            SqlDdlBuilder sqlDdlBuilder = new SqlDdlBuilder();

            foreach (EntityContainer entityContainer in itemCollection.GetItems <EntityContainer>())
            {
                IOrderedEnumerable <EntitySet> source = entityContainer.BaseEntitySets.OfType <EntitySet>().OrderBy <EntitySet, string>((Func <EntitySet, string>)(s => s.Name));
                if (createSchemas)
                {
                    foreach (string schema in (IEnumerable <string>) new HashSet <string>(source.Select <EntitySet, string>((Func <EntitySet, string>)(s => SqlDdlBuilder.GetSchemaName(s)))).OrderBy <string, string>((Func <string, string>)(s => s)))
                    {
                        if (schema != "dbo")
                        {
                            sqlDdlBuilder.AppendCreateSchema(schema);
                        }
                    }
                }
                foreach (EntitySet entitySet in (IEnumerable <EntitySet>)entityContainer.BaseEntitySets.OfType <EntitySet>().OrderBy <EntitySet, string>((Func <EntitySet, string>)(s => s.Name)))
                {
                    sqlDdlBuilder.AppendCreateTable(entitySet);
                }
                foreach (AssociationSet associationSet in (IEnumerable <AssociationSet>)entityContainer.BaseEntitySets.OfType <AssociationSet>().OrderBy <AssociationSet, string>((Func <AssociationSet, string>)(s => s.Name)))
                {
                    sqlDdlBuilder.AppendCreateForeignKeys(associationSet);
                }
            }
            return(sqlDdlBuilder.GetCommandText());
        }
示例#3
0
        // <summary>
        // Helper function for generating the scripts for tables &amp; constraints.
        // </summary>
        internal static List <string> CreateObjectsScript(StoreItemCollection itemCollection, bool returnWarnings)
        {
            var builder = new SqlDdlBuilder();

            // Iterate over the container.
            foreach (var container in itemCollection.GetItems <EntityContainer>())
            {
                // Generate create table statements.
                foreach (var set in container.BaseEntitySets)
                {
                    // If it is a type of entitySet, generate Create Table statements.
                    var entitySet = set as EntitySet;
                    if (entitySet != null)
                    {
                        builder.AppendCreateTable(entitySet);
                    }
                }

                // Generate Foreign Key constraints.
                foreach (var set in container.BaseEntitySets)
                {
                    // If it is association set, generate Foreign Key constraints.
                    var associationSet = set as AssociationSet;
                    if (associationSet != null)
                    {
                        builder.AppendCreateForeignKeys(associationSet);
                    }
                }
            }

            // Return the final command text.
            return(builder.GetCommandText(returnWarnings));
        }
示例#4
0
        internal static string CreateObjectsScript(StoreItemCollection itemCollection)
        {
            DdlBuilder builder = new DdlBuilder();

            foreach (EntityContainer container in itemCollection.GetItems <EntityContainer>())
            {
                var entitySets = container.BaseEntitySets.OfType <EntitySet>().OrderBy(s => s.Name);

                var schemas = new HashSet <string>(entitySets.Select(s => GetSchemaName(s)));
                foreach (string schema in schemas.OrderBy(s => s))
                {
                    // don't bother creating default schema
                    if (schema != "dbo")
                    {
                        builder.AppendCreateSchema(schema);
                    }
                }

                foreach (EntitySet entitySet in container.BaseEntitySets.OfType <EntitySet>().OrderBy(s => s.Name))
                {
                    builder.AppendCreateTable(entitySet);
                }

                foreach (AssociationSet associationSet in container.BaseEntitySets.OfType <AssociationSet>().OrderBy(s => s.Name))
                {
                    builder.AppendCreateForeignKeys(associationSet);
                }
            }
            return(builder.GetCommandText());
        }
示例#5
0
        protected override string DbCreateDatabaseScript(string providerManifestToken,
                                                         StoreItemCollection storeItemCollection)
        {
            StringBuilder sql = new StringBuilder();

            sql.AppendLine("-- MySql script");
            sql.AppendLine("-- Created on " + DateTime.Now);

            if (serverVersion == null)
            {
                serverVersion = new Version(providerManifestToken == null ? "5.5" : providerManifestToken);
            }

            foreach (EntityContainer container in storeItemCollection.GetItems <EntityContainer>())
            {
                // now output the tables
                foreach (EntitySet es in container.BaseEntitySets.OfType <EntitySet>())
                {
                    sql.Append(GetTableCreateScript(es));
                }

                // now output the foreign keys
                foreach (AssociationSet a in container.BaseEntitySets.OfType <AssociationSet>())
                {
                    sql.Append(GetAssociationCreateScript(a.ElementType));
                }
            }

            return(sql.ToString());
        }
        internal static string DropDatabaseScript(string databaseName, StoreItemCollection itemCollection)
        {
            EFOracleDdlBuilder oracleDdlBuilder = new EFOracleDdlBuilder();

            foreach (EntityContainer entityContainer in itemCollection.GetItems <EntityContainer>())
            {
                entityContainer.BaseEntitySets.OfType <EntitySet>().OrderBy <EntitySet, string>((Func <EntitySet, string>)(s => s.Name));
                foreach (EntitySet entitySet in (IEnumerable <EntitySet>)entityContainer.BaseEntitySets.OfType <EntitySet>().OrderBy <EntitySet, string>((Func <EntitySet, string>)(s => s.Name)))
                {
                    oracleDdlBuilder.AppendSql("drop table ");
                    oracleDdlBuilder.AppendIdentifier(entitySet);
                    oracleDdlBuilder.AppendSql(" cascade constraints \n\n");
                    oracleDdlBuilder.AppendSql("drop sequence ");
                    oracleDdlBuilder.AppendIdentifier(EFOracleDdlBuilder.GetSchemaName(entitySet));
                    oracleDdlBuilder.AppendSql(".");
                    string str = OracleMigrationSqlGenerator.SequencePrefix + OracleMigrationSqlGenerator.NameSeparator + EFOracleDdlBuilder.GetTableName(entitySet);
                    if (Encoding.UTF8.GetByteCount(str) > OracleMigrationSqlGenerator.MaxIdentifierLengthBytes)
                    {
                        str = OracleMigrationSqlGenerator.DeriveObjectName((string)null, str, 30);
                    }
                    oracleDdlBuilder.AppendIdentifier(str);
                    oracleDdlBuilder.AppendSql("\n\n");
                }
            }
            oracleDdlBuilder.AppendSql("drop table ");
            oracleDdlBuilder.AppendIdentifier("__MigrationHistory");
            oracleDdlBuilder.AppendSql(" cascade constraints \n\n");
            oracleDdlBuilder.AppendSql("drop table ");
            oracleDdlBuilder.AppendIdentifier("EdmMetadata");
            oracleDdlBuilder.AppendSql(" cascade constraints \n\n");
            return(oracleDdlBuilder.stringBuilder.ToString());
        }
        public static EdmModel ToEdmModel(this StoreItemCollection storeItemCollection)
        {
            Debug.Assert(storeItemCollection != null, "storeItemCollection != null");

            var container = storeItemCollection.GetItems <EntityContainer>().SingleOrDefault();
            var edmModel  =
                container != null
                    ? EdmModel.CreateStoreModel(container, null, null, storeItemCollection.StoreSchemaVersion)
                    : new EdmModel(DataSpace.SSpace, storeItemCollection.StoreSchemaVersion);

            foreach (var entityType in storeItemCollection.GetItems <EntityType>())
            {
                edmModel.AddItem(entityType);
            }

            foreach (var associationType in storeItemCollection.GetItems <AssociationType>())
            {
                edmModel.AddItem(associationType);
            }

            return(edmModel);
        }
示例#8
0
 static IEnumerable <string> Tables(StoreItemCollection storeItems)
 {
     foreach (var entitySet in storeItems.GetItems <EntityContainer>()[0].BaseEntitySets.OfType <EntitySet>())
     {
         var result = new StringBuilder();
         var additionalColumnComments = new Dictionary <string, string>();
         result.AppendFormat("RECREATE TABLE {0} (", SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(entitySet)));
         result.AppendLine();
         foreach (var property in MetadataHelpers.GetProperties(entitySet.ElementType))
         {
             var column = GenerateColumn(property);
             result.Append("\t");
             result.Append(column.ColumnName);
             result.Append(",");
             result.AppendLine();
             foreach (var item in column.ColumnComments)
             {
                 additionalColumnComments.Add(item.Key, item.Value);
             }
         }
         result.AppendFormat("CONSTRAINT {0} PRIMARY KEY ({1})",
                             SqlGenerator.QuoteIdentifier(string.Format("PK_{0}", MetadataHelpers.GetTableName(entitySet))),
                             string.Join(", ", entitySet.ElementType.KeyMembers.Select(pk => SqlGenerator.QuoteIdentifier(pk.Name))));
         result.AppendLine();
         result.Append(");");
         result.AppendLine();
         foreach (var identity in entitySet.ElementType.KeyMembers.Where(pk => MetadataHelpers.IsStoreGeneratedIdentity(pk)).Select(i => i.Name))
         {
             result.AppendLine(string.Concat("CREATE GENERATOR GEN_", MetadataHelpers.GetTableName(entitySet), "_", identity, ";"));
             result.AppendLine(string.Concat("SET GENERATOR GEN_", MetadataHelpers.GetTableName(entitySet), "_", identity, " TO 0;"));
             result.AppendLine("set term !!;");
             result.AppendLine(string.Concat("CREATE TRIGGER ", MetadataHelpers.GetTableName(entitySet), "_BI FOR ", SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(entitySet))));
             result.AppendLine("ACTIVE BEFORE INSERT POSITION 0");
             result.AppendLine("AS");
             result.AppendLine("BEGIN");
             result.AppendLine(string.Concat("if (NEW.", SqlGenerator.QuoteIdentifier(identity), " is NULL OR NEW.", SqlGenerator.QuoteIdentifier(identity), "=0) then NEW.", SqlGenerator.QuoteIdentifier(identity), " = GEN_ID(GEN_", MetadataHelpers.GetTableName(entitySet), "_", identity, ", 1);"));
             result.AppendLine("END!!");
             result.AppendLine("set term ; !!");
             additionalColumnComments.Add(identity, "#PK_GEN#");
         }
         foreach (var comment in additionalColumnComments)
         {
             result.AppendFormat("COMMENT ON COLUMN {0}.{1} IS '{2}';",
                                 SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(entitySet)),
                                 SqlGenerator.QuoteIdentifier(comment.Key),
                                 comment.Value);
             result.AppendLine();
         }
         yield return(result.ToString());
     }
 }
        /// <summary>
        /// Creates a database indicated by connection and creates schema objects (tables, primary keys, foreign keys) based on the contents of a StoreItemCollection.
        /// Note: in EF 6.1 this is not called if the provider implements Migration classes
        /// Note: we can't create database for Jet Connections
        /// </summary>
        /// <param name="connection">Connection to a non-existent database that needs to be created and populated with the store objects indicated with the storeItemCollection parameter.</param>
        /// <param name="commandTimeout">Execution timeout for any commands needed to create the database.</param>
        /// <param name="storeItemCollection">The collection of all store items based on which the script should be created.</param>
        /// <exception cref="System.ArgumentNullException">
        /// connection must not be null
        /// or
        /// storeItemCollection must not be null
        /// </exception>
        /// <exception cref="System.ArgumentException">The connection is not of type 'JetConnection'.</exception>
        protected override void DbCreateDatabase(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection)
        {
            if (connection == null)
            {
                throw new ArgumentNullException("connection must not be null");
            }

            if (storeItemCollection == null)
            {
                throw new ArgumentNullException("storeItemCollection must not be null");
            }

            JetConnection jetConnection = connection as JetConnection;

            if (jetConnection == null)
            {
                throw new ArgumentException("The connection is not of type 'JetConnection'.");
            }



            ConnectionState oldConnectionState = connection.State;

            if (oldConnectionState == ConnectionState.Closed)
            {
                connection.Open();
            }

            foreach (EntityContainer container in storeItemCollection.GetItems <EntityContainer>())
            {
                var entitySets = container.BaseEntitySets.OfType <EntitySet>().OrderBy(s => s.Name);

                foreach (EntitySet entitySet in container.BaseEntitySets.OfType <EntitySet>().OrderBy(s => s.Name))
                {
                    string createObjectScript = JetCreateDatabaseSqlGenerator.CreateObjectScript(entitySet);
                    jetConnection.CreateCommand(createObjectScript, commandTimeout).ExecuteNonQuery();
                }

                foreach (AssociationSet associationSet in container.BaseEntitySets.OfType <AssociationSet>().OrderBy(s => s.Name))
                {
                    string createObjectScript = JetCreateDatabaseSqlGenerator.CreateObjectScript(associationSet);
                    jetConnection.CreateCommand(createObjectScript, commandTimeout).ExecuteNonQuery();
                }
            }

            if (oldConnectionState == ConnectionState.Closed)
            {
                connection.Close();
            }
        }
示例#10
0
        public EdmMapping(EdmItemCollection conceptual, StoreItemCollection store, XmlReader mappingReader)
        {
            // Pull mapping xml out
            var mappingDoc = new XmlDocument();

            mappingDoc.Load(mappingReader);

            var entitySets      = conceptual.GetItems <EntityContainer>().Single().BaseEntitySets.OfType <System.Data.Entity.Core.Metadata.Edm.EntitySet>();
            var associationSets = conceptual.GetItems <EntityContainer>().Single().BaseEntitySets.OfType <System.Data.Entity.Core.Metadata.Edm.AssociationSet>();
            var tableSets       = store.GetItems <EntityContainer>().Single().BaseEntitySets.OfType <System.Data.Entity.Core.Metadata.Edm.EntitySet>().ToArray();

            this.EntityMappings     = BuildEntityMappings(mappingDoc, entitySets, tableSets);
            this.ManyToManyMappings = BuildManyToManyMappings(mappingDoc, associationSets, tableSets);
        }
示例#11
0
        public EdmMapping(EntityModelSchemaGenerator mcGenerator, StoreItemCollection store)
        {
            var mappingDoc = new XmlDocument();
            var mappingXml = new StringBuilder();

            using (var textWriter = new StringWriter(mappingXml))
                mcGenerator.WriteStorageMapping(new XmlTextWriter(textWriter));

            mappingDoc.LoadXml(mappingXml.ToString());

            var entitySets      = mcGenerator.EntityContainer.BaseEntitySets.OfType <EntitySet>();
            var associationSets = mcGenerator.EntityContainer.BaseEntitySets.OfType <AssociationSet>();
            var tableSets       = store.GetItems <EntityContainer>().Single().BaseEntitySets.OfType <EntitySet>();

            EntityMappings     = BuildEntityMappings(mappingDoc, entitySets, tableSets);
            ManyToManyMappings = BuildManyToManyMappings(mappingDoc, associationSets, tableSets);
        }
        /// <summary>
        /// Main driver function.
        /// </summary>
        /// <param name="args"></param>
        public static void Generate(string outputFileName)
        {
            //The following functions are omitted because they have counterparts in the BCL
            string[] omittedFunctions = new[]
            {
                "Sum", "Min", "Max", "Average", "Avg",
                "Count", "BigCount",
                "Trim", "RTrim", "LTrim",
                "Concat", "Length", "Substring",
                "Replace", "IndexOf", "ToUpper", "ToLower",
                "Contains", "StartsWith", "EndsWith", "Year", "Month", "Day",
                "DayOfYear", "Hour", "Minute", "Second", "Millisecond", "CurrentDateTime", "CurrentDateTimeOffset",
                "CurrentUtcDateTime",
                "BitwiseAnd", "BitwiseOr", "BitwiseXor", "BitwiseNot",
                "Round", "Abs", "Power", "NewGuid",
                "Floor", "Ceiling",
            };

            //The following functions are omitted from SqlFunctions because they already exist in EntityFunctions
            string[] omittedSqlFunctions = new[]
            {
                "STDEV", "STDEVP", "VAR", "VARP", "COUNT_BIG",
                "Left", "Right", "Reverse", "GetTotalOffsetMinutes",
                "TruncateTime", "CreateDateTime",
                "CreateDateTimeOffset", "CreateTime", "Add", "Diff",
                "Truncate", "SYSDATETIME", "SYSUTCDATETIME", "SYSDATETIMEOFFSET",
                "LEN", "LOWER", "UPPER", "NEWID",
            };

            //Generate Sql Server function stubs
            String ssdl = @"<Schema Namespace='LinqFunctionStubsGenerator' Alias='Self' Provider='SampleEntityFrameworkProvider' ProviderManifestToken='2008' xmlns='http://schemas.microsoft.com/ado/2006/04/edm/ssdl'></Schema>";

            XmlReader[] xmlReaders = new XmlReader[1];
            xmlReaders[0] = XmlReader.Create(new StringReader(ssdl));

            StoreItemCollection       storeItemCollection = new StoreItemCollection(xmlReaders);
            IEnumerable <EdmFunction> sqlFunctions        = storeItemCollection.GetItems <EdmFunction>()
                                                            .Where(f => f.NamespaceName == "SqlServer")
                                                            .Where(f => !(omittedFunctions.Concat(omittedSqlFunctions)).Contains(f.Name, StringComparer.OrdinalIgnoreCase));

            FunctionStubFileWriter sqlStubsFileWriter = new FunctionStubFileWriter(sqlFunctions, GetFunctionNamingDictionary(), GetParameterNamingDictionary());

            sqlStubsFileWriter.GenerateToFile(outputFileName, "SampleEntityFrameworkProvider", "SampleSqlFunctions", "SqlServer", true);
        }
示例#13
0
 static IEnumerable <string> GenerateForeignKeys(StoreItemCollection storeItems)
 {
     foreach (var associationSet in storeItems.GetItems <EntityContainer>()[0].BaseEntitySets.OfType <AssociationSet>())
     {
         var result = new StringBuilder();
         ReferentialConstraint constraint = associationSet.ElementType.ReferentialConstraints.Single <ReferentialConstraint>();
         AssociationSetEnd     end        = associationSet.AssociationSetEnds[constraint.FromRole.Name];
         AssociationSetEnd     end2       = associationSet.AssociationSetEnds[constraint.ToRole.Name];
         result.AppendFormat("ALTER TABLE {0}.{1} ADD FOREIGN KEY ({2}) REFERENCES {3}.{4}({5}){6};",
                             SqlGenerator.QuoteIdentifier(MetadataHelpers.GetSchemaName(end2.EntitySet)),
                             SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(end2.EntitySet)),
                             string.Join(", ", constraint.ToProperties.Select(fk => SqlGenerator.QuoteIdentifier(fk.Name))),
                             SqlGenerator.QuoteIdentifier(MetadataHelpers.GetSchemaName(end.EntitySet)),
                             SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(end.EntitySet)),
                             string.Join(", ", constraint.FromProperties.Select(pk => SqlGenerator.QuoteIdentifier(pk.Name))),
                             end.CorrespondingAssociationEndMember.DeleteBehavior == OperationAction.Cascade ? " ON DELETE CASCADE" : string.Empty);
         yield return(result.ToString());
     }
 }
示例#14
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="DbSchemaKey" /> class.
        /// </summary>
        /// <param name="storeItemCollection">
        ///     The store item collection that the corresponding <see cref="T:DbSchema"/> is
        ///     based on.
        /// </param>
        public DbSchemaKey(StoreItemCollection storeItemCollection)
        {
            // Find container
            EntityContainer entityContainer =
                storeItemCollection.GetItems <EntityContainer>().FirstOrDefault();

            StringBuilder builder = new StringBuilder();

            builder.Append(entityContainer.Name);
            builder.Append("(");

            // Find entity sets
            IEnumerable <EntitySet> sets = entityContainer
                                           .BaseEntitySets
                                           .OfType <EntitySet>()
                                           .OrderBy(s => s.GetTableName());

            foreach (EntitySet set in sets)
            {
                builder.Append(set.GetTableName());
                builder.Append("(");

                IEnumerable <EdmProperty> properties =
                    set.ElementType.Properties.OrderBy(p => p.GetColumnName());

                foreach (EdmProperty property in properties)
                {
                    builder.Append(property.GetColumnName());
                    builder.Append("(");

                    builder.Append(property.TypeUsage.EdmType.FullName);

                    builder.Append(")");
                }

                builder.Append(")");
            }

            builder.Append(")");

            this.innerKey = builder.ToString();
        }
        internal static string CreateTableExistsScript(StoreItemCollection itemCollection, out int count)
        {
            int num = 0;
            EFOracleDdlBuilder oracleDdlBuilder = new EFOracleDdlBuilder();

            oracleDdlBuilder.AppendSql("select count(*) from ");
            oracleDdlBuilder.AppendSql("all_tables");
            oracleDdlBuilder.AppendSql(" where ");
            foreach (EntityContainer entityContainer in itemCollection.GetItems <EntityContainer>())
            {
                entityContainer.BaseEntitySets.OfType <EntitySet>().OrderBy <EntitySet, string>((Func <EntitySet, string>)(s => s.Name));
                foreach (EntitySet entitySet in (IEnumerable <EntitySet>)entityContainer.BaseEntitySets.OfType <EntitySet>().OrderBy <EntitySet, string>((Func <EntitySet, string>)(s => s.Name)))
                {
                    string schemaName = EFOracleDdlBuilder.GetSchemaName(entitySet);
                    ++num;
                    if (num > 1)
                    {
                        oracleDdlBuilder.AppendSql(" or ");
                    }
                    oracleDdlBuilder.AppendSql("(");
                    oracleDdlBuilder.AppendSql("owner=");
                    if (entitySet.Name != "HistoryRow" || entitySet.Name == "HistoryRow" && schemaName != "dbo")
                    {
                        oracleDdlBuilder.AppendSql("'");
                        oracleDdlBuilder.AppendSql(schemaName);
                        oracleDdlBuilder.AppendSql("'");
                    }
                    else
                    {
                        oracleDdlBuilder.AppendSql("user");
                    }
                    oracleDdlBuilder.AppendSql(" and ");
                    oracleDdlBuilder.AppendSql("table_name=");
                    oracleDdlBuilder.AppendSql("'");
                    oracleDdlBuilder.AppendSql(EFOracleDdlBuilder.GetTableName(entitySet));
                    oracleDdlBuilder.AppendSql("'");
                    oracleDdlBuilder.AppendSql(")");
                }
            }
            count = num;
            return(oracleDdlBuilder.GetCommandText());
        }
示例#16
0
 static IEnumerable <string> Tables(StoreItemCollection storeItems)
 {
     foreach (var entitySet in storeItems.GetItems <EntityContainer>()[0].BaseEntitySets.OfType <EntitySet>())
     {
         var result = new StringBuilder();
         var additionalColumnComments = new Dictionary <string, string>();
         result.AppendFormat("RECREATE TABLE {0} (", SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(entitySet)));
         result.AppendLine();
         foreach (var property in MetadataHelpers.GetProperties(entitySet.ElementType))
         {
             var column = GenerateColumn(property);
             result.Append("\t");
             result.Append(column.ColumnName);
             result.Append(",");
             result.AppendLine();
             foreach (var item in column.ColumnComments)
             {
                 additionalColumnComments.Add(item.Key, item.Value);
             }
         }
         result.AppendFormat("CONSTRAINT {0} PRIMARY KEY ({1})",
                             SqlGenerator.QuoteIdentifier(string.Format("PK_{0}", MetadataHelpers.GetTableName(entitySet))),
                             string.Join(", ", entitySet.ElementType.KeyMembers.Select(pk => SqlGenerator.QuoteIdentifier(pk.Name))));
         result.AppendLine();
         result.Append(");");
         result.AppendLine();
         foreach (var identity in entitySet.ElementType.KeyMembers.Where(pk => MetadataHelpers.IsStoreGeneratedIdentity(pk)).Select(i => i.Name))
         {
             additionalColumnComments.Add(identity, "#PK_GEN#");
         }
         foreach (var comment in additionalColumnComments)
         {
             result.AppendFormat("COMMENT ON COLUMN {0}.{1} IS '{2}';",
                                 SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(entitySet)),
                                 SqlGenerator.QuoteIdentifier(comment.Key),
                                 comment.Value);
             result.AppendLine();
         }
         yield return(result.ToString());
     }
 }
示例#17
0
 static IEnumerable <string> GenerateTables(StoreItemCollection storeItems)
 {
     foreach (var entitySet in storeItems.GetItems <EntityContainer>()[0].BaseEntitySets.OfType <EntitySet>())
     {
         var result     = new StringBuilder();
         var tableName  = MetadataHelpers.GetTableName(entitySet);
         var schemaName = MetadataHelpers.GetSchemaName(entitySet);
         result.AppendFormat("CREATE TABLE {0}.{1} (", SqlGenerator.QuoteIdentifier(schemaName), SqlGenerator.QuoteIdentifier(tableName));
         result.AppendLine();
         result.Append("\t");
         result.Append(string.Join("," + Environment.NewLine + "\t", MetadataHelpers.GetProperties(entitySet.ElementType).Select(p => GenerateColumn(p))));
         result.Append(");");
         result.AppendLine();
         result.AppendFormat("ALTER TABLE {0}.{1} ADD PRIMARY KEY ({2});",
                             SqlGenerator.QuoteIdentifier(schemaName),
                             SqlGenerator.QuoteIdentifier(tableName),
                             string.Join(", ", entitySet.ElementType.KeyMembers.Select(pk => SqlGenerator.QuoteIdentifier(pk.Name))));
         result.AppendLine();
         yield return(result.ToString());
     }
 }
        internal static string CreateObjectsScript(StoreItemCollection itemCollection, bool execScript = false)
        {
            var builder = new DdlBuilder(execScript);

            foreach (var container in itemCollection.GetItems <EntityContainer>())
            {
                builder._tableIndexService.LoadTableIndexes(container);

                foreach (var entitySet in container.BaseEntitySets.OfType <EntitySet>().OrderBy(s => s.Name))
                {
                    builder.AppendCreateTable(entitySet);
                }

                foreach (var associationSet in container.BaseEntitySets.OfType <AssociationSet>().OrderBy(s => s.Name))
                {
                    builder.AppendCreateForeignKeyRelation(associationSet);
                }
            }

            return(builder.GetCommandText());
        }
示例#19
0
        public static string DropObjects(StoreItemCollection itemCollection)
        {
            var builder = new SqlScripts();

            foreach (var container in itemCollection.GetItems <EntityContainer>())
            {
                var entitySets = container.BaseEntitySets.OfType <EntitySet>().OrderBy(s => s.Name);

                foreach (var associationSet in container.BaseEntitySets.OfType <AssociationSet>().OrderBy(s => s.Name))
                {
                    builder.AppendDropForeignKeys(associationSet);
                }

                foreach (var entitySet in container.BaseEntitySets.OfType <EntitySet>().OrderBy(s => s.Name))
                {
                    builder.AppendDropTable(entitySet);
                }
            }

            return(builder.GetCommandText());
        }
		static IEnumerable<string> Tables(StoreItemCollection storeItems)
		{
			foreach (var entitySet in storeItems.GetItems<EntityContainer>()[0].BaseEntitySets.OfType<EntitySet>())
			{
				var result = new StringBuilder();
				var additionalColumnComments = new Dictionary<string, string>();
				result.AppendFormat("RECREATE TABLE {0} (", SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(entitySet)));
				result.AppendLine();
				foreach (var property in MetadataHelpers.GetProperties(entitySet.ElementType))
				{
					var column = GenerateColumn(property);
					result.Append("\t");
					result.Append(column.ColumnName);
					result.Append(",");
					result.AppendLine();
					foreach (var item in column.ColumnComments)
						additionalColumnComments.Add(item.Key, item.Value);
				}
				result.AppendFormat("CONSTRAINT {0} PRIMARY KEY ({1})",
					SqlGenerator.QuoteIdentifier(string.Format("PK_{0}", MetadataHelpers.GetTableName(entitySet))),
					string.Join(", ", entitySet.ElementType.KeyMembers.Select(pk => SqlGenerator.QuoteIdentifier(pk.Name))));
				result.AppendLine();
				result.Append(");");
				result.AppendLine();
				foreach (var identity in entitySet.ElementType.KeyMembers.Where(pk => MetadataHelpers.IsStoreGeneratedIdentity(pk)).Select(i => i.Name))
				{
					additionalColumnComments.Add(identity, "#PK_GEN#");
				}
				foreach (var comment in additionalColumnComments)
				{
					result.AppendFormat("COMMENT ON COLUMN {0}.{1} IS '{2}';",
						SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(entitySet)),
						SqlGenerator.QuoteIdentifier(comment.Key),
						comment.Value);
					result.AppendLine();
				}
				yield return result.ToString();
			}
		}
        internal static string CreateObjectsScript(StoreItemCollection itemCollection)
        {
            JetCreateDatabaseSqlGenerator builder = new JetCreateDatabaseSqlGenerator();

            foreach (EntityContainer container in itemCollection.GetItems <EntityContainer>())
            {
                var entitySets = container.BaseEntitySets.OfType <EntitySet>().OrderBy(s => s.Name);

                foreach (EntitySet entitySet in container.BaseEntitySets.OfType <EntitySet>().OrderBy(s => s.Name))
                {
                    builder.AppendCreateTable(entitySet);
                    builder.AppendSql(";");
                }

                foreach (AssociationSet associationSet in container.BaseEntitySets.OfType <AssociationSet>().OrderBy(s => s.Name))
                {
                    builder.AppendCreateForeignKeys(associationSet);
                    builder.AppendSql(";");
                }
            }
            return(builder.GetCommandText());
        }
示例#22
0
        public bool IsInitialized(StoreItemCollection edmStoreSchema)
        {
            // TODO: Lock
            if (this.database == null)
            {
                return(false);
            }

            // Find container
            EntityContainer entityContainer = edmStoreSchema.GetItems <EntityContainer>().FirstOrDefault();

            foreach (EntitySet entitySet in entityContainer.BaseEntitySets.OfType <EntitySet>())
            {
                // TODO: Verify fields
                if (!this.Internal.ContainsTable(entitySet.GetTableName()))
                {
                    return(false);
                }
            }

            return(true);
        }
示例#23
0
 static IEnumerable<string> ForeignKeyConstraints(StoreItemCollection storeItems)
 {
     foreach (var associationSet in storeItems.GetItems<EntityContainer>()[0].BaseEntitySets.OfType<AssociationSet>())
     {
         var result = new StringBuilder();
         ReferentialConstraint constraint = associationSet.ElementType.ReferentialConstraints.Single<ReferentialConstraint>();
         AssociationSetEnd end = associationSet.AssociationSetEnds[constraint.FromRole.Name];
         AssociationSetEnd end2 = associationSet.AssociationSetEnds[constraint.ToRole.Name];
         result.AppendFormat("ALTER TABLE {0} ADD CONSTRAINT {1} FOREIGN KEY ({2})",
             SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(end2.EntitySet)),
             SqlGenerator.QuoteIdentifier(string.Format("FK_{0}", associationSet.Name)),
             constraint.ToProperties.Select(fk => SqlGenerator.QuoteIdentifier(fk.Name)).StringJoin(", "));
         result.AppendLine();
         result.AppendFormat("REFERENCES {0}({1})",
             SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(end.EntitySet)),
             constraint.FromProperties.Select(pk => SqlGenerator.QuoteIdentifier(pk.Name)).StringJoin(", "));
         result.AppendLine();
         result.AppendFormat("ON DELETE {0}",
             end.CorrespondingAssociationEndMember.DeleteBehavior == OperationAction.Cascade ? "CASCADE" : "NO ACTION");
         result.Append(";");
         yield return result.ToString();
     }
 }
示例#24
0
 static IEnumerable <string> ForeignKeyConstraints(StoreItemCollection storeItems)
 {
     foreach (var associationSet in storeItems.GetItems <EntityContainer>()[0].BaseEntitySets.OfType <AssociationSet>())
     {
         var result     = new StringBuilder();
         var constraint = associationSet.ElementType.ReferentialConstraints.Single <ReferentialConstraint>();
         var end        = associationSet.AssociationSetEnds[constraint.FromRole.Name];
         var end2       = associationSet.AssociationSetEnds[constraint.ToRole.Name];
         result.AppendFormat("ALTER TABLE {0} ADD CONSTRAINT {1} FOREIGN KEY ({2})",
                             SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(end2.EntitySet)),
                             SqlGenerator.QuoteIdentifier(string.Format("FK_{0}", associationSet.Name)),
                             string.Join(", ", constraint.ToProperties.Select(fk => SqlGenerator.QuoteIdentifier(fk.Name))));
         result.AppendLine();
         result.AppendFormat("REFERENCES {0}({1})",
                             SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(end.EntitySet)),
                             string.Join(", ", constraint.FromProperties.Select(pk => SqlGenerator.QuoteIdentifier(pk.Name))));
         result.AppendLine();
         result.AppendFormat("ON DELETE {0}",
                             end.CorrespondingAssociationEndMember.DeleteBehavior == OperationAction.Cascade ? "CASCADE" : "NO ACTION");
         result.Append(";");
         yield return(result.ToString());
     }
 }
        internal static string CreateObjectsScript(StoreItemCollection itemCollection, string providerManifestToken)
        {
            EFOracleDdlBuilder oracleDdlBuilder = new EFOracleDdlBuilder();

            foreach (EntityContainer entityContainer in itemCollection.GetItems <EntityContainer>())
            {
                entityContainer.BaseEntitySets.OfType <EntitySet>().OrderBy <EntitySet, string>((Func <EntitySet, string>)(s => s.Name));
                foreach (EntitySet entitySet in (IEnumerable <EntitySet>)entityContainer.BaseEntitySets.OfType <EntitySet>().OrderBy <EntitySet, string>((Func <EntitySet, string>)(s => s.Name)))
                {
                    oracleDdlBuilder.AppendCreateTable(entitySet, providerManifestToken);
                }
                foreach (AssociationSet associationSet in (IEnumerable <AssociationSet>)entityContainer.BaseEntitySets.OfType <AssociationSet>().OrderBy <AssociationSet, string>((Func <AssociationSet, string>)(s => s.Name)))
                {
                    oracleDdlBuilder.AppendCreateForeignKeys(associationSet);
                }
                for (int index = 0; index < EFOracleDdlBuilder.SequenceAndTriggerList.Count; ++index)
                {
                    oracleDdlBuilder.AppendSql(EFOracleDdlBuilder.SequenceAndTriggerList[index]);
                }
                EFOracleDdlBuilder.SequenceAndTriggerList.Clear();
            }
            return(oracleDdlBuilder.GetCommandText());
        }
        Visit_DbVariableReferenceExpression_creates_equivalent_legacy_DbVariableReferenceExpression_for_SSpace_type()
        {
            var variableReference =
                TypeUsage
                .CreateDefaultTypeUsage(
                    _storeItemCollection.GetItems <EntityType>().Single(e => e.Name == "Entities"))
                .Variable("variable");

            var legacyVariableReference =
                _legacyDbExpressionConverter.Visit(variableReference) as
                LegacyCommandTrees.DbVariableReferenceExpression;

            Assert.NotNull(legacyVariableReference);
            Assert.Equal(LegacyCommandTrees.DbExpressionKind.VariableReference, legacyVariableReference.ExpressionKind);
            Assert.Equal(variableReference.VariableName, legacyVariableReference.VariableName);

            TypeUsageVerificationHelper
            .VerifyTypeUsagesEquivalent(legacyVariableReference.ResultType, variableReference.ResultType);
        }
示例#27
0
        static void Main(string[] args)
        {
            Console.WriteLine("Entity Frameworks CodeGenerationTools Demo Program.\n");

            //I had problems with accessing Dictionary by [] index, so quickly used these
            //to check in normal C# usage.
            //var tc = new TestCollections();
            //tc.TestCollections2();

            try
            {
                //As this program only reads and interprets the XML within the EDMX,
                //there is no need for a ConnectionString in the App.Config and
                //no connection is made to a database.

                //Since this is a test program, let's assume you are executing from .\bin\Debug
                var currentdirectory = Environment.CurrentDirectory;
                var inputFile        = @"..\..\Model1.edmx";
                inputFile = Path.Combine(currentdirectory, inputFile);

                //Demo 1
                //EFFluentUtility is from
                //http://visualstudiogallery.msdn.microsoft.com/5d663b99-ed3b-481d-b7bc-b947d2457e3c
                //By opening the VSIX (DbContextFluentTemplate_V50, which is a ZIP) I've taken a
                //copy of "CSharpDbContextFluent.Mapping.tt" from the ItemTemplate.
                //Then copied the supporting classes from the template and
                //entered here in the CodeGenerationToolsLibrary project as a .Net Class here.
                //I've used the Mapping.tt because it is the most complex,
                //and shows how to obtain the Mapping info used to
                //create the EntityConfiguration from the EDMX.
                //
                // See PropertyToColumnMapping and ManyToManyMappings from
                // MetadataLoadResult
                //
                EF5FluentUtility   efu = new EF5FluentUtility();
                MetadataLoadResult mlr = efu.LoadMetadata(inputFile);

                var a = mlr.EdmItems;
                var b = mlr.ManyToManyMappings;
                var c = mlr.PropertyToColumnMapping;
                var d = mlr.TphMappings;

                //Obtain the EntityContainer from the ItemsCollection
                var container = mlr.EdmItems.GetItems <EntityContainer>()[0];

                //Iterate all the EntitySets and Properties
                //EntitySet are as in "People", where the EntityType is "Person"
                foreach (var entityset in container.BaseEntitySets.OfType <EntitySet>().OrderBy(e => e.Name))
                {
                    var entitysetname = entityset.Name;
                    var entityname    = entityset.ElementType.Name;
                    var entitytype    = entityset.ElementType;
                    var declaringtype = entityset.ElementType.NavigationProperties[0].DeclaringType;

                    //Navigation Properties for a particular Entity
                    var collectionNavigations1 = entityset.ElementType.NavigationProperties.Where(np => np.DeclaringType == entityset.ElementType);

                    // Find m:m relationshipsto configure for a particular Entity
                    var manyManyRelationships = entityset.ElementType.NavigationProperties
                                                .Where(np =>
                                                       //np.DeclaringType is EntityType &&
                                                       np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many &&
                                                       np.FromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many
                                                       // Ensures we only configure from one end.
                                                       // Convention is to have source on the left, as it would be diagrammatically.
                                                       && np.RelationshipType.RelationshipEndMembers.First() == np.FromEndMember)
                                                .ToArray();

                    //Now process the M:Ms
                    foreach (var navProperty in manyManyRelationships)
                    {
                        var otherNavProperty = navProperty.ToEndMember.GetEntityType().NavigationProperties.Where(n => n.RelationshipType == navProperty.RelationshipType && n != navProperty).Single();
                        var association      = (AssociationType)navProperty.RelationshipType;

                        //This did not work in the T4 Template.
                        var mapping1 = mlr.ManyToManyMappings[association];

                        var mapping2 = mlr.ManyToManyMappings.Where(m => m.Key.Name == association.Name).FirstOrDefault().Value;
                        var item1    = mapping1.Item1;

                        //This did not work in the T4 Template.
                        var leftKeyMappings1 = mapping1.Item2[navProperty.ToEndMember];
                        var leftKeyMappings2 = mapping1.Item2.Where(np => np.Key.Name == navProperty.ToEndMember.Name).FirstOrDefault().Value;

                        // Need to ensure that FKs are declared in the same order as the PK properties on each principal type
                        var leftType  = (EntityType)navProperty.DeclaringType;
                        var rightType = (EntityType)otherNavProperty.DeclaringType;

                        //Access using Index [navProperty.FromEndMember] did not work within template.
                        var leftKeyMappings  = mapping1.Item2.Where(np => np.Key.Name == navProperty.FromEndMember.Name).FirstOrDefault().Value;      //[navProperty.FromEndMember];
                        var rightKeyMappings = mapping1.Item2.Where(np => np.Key.Name == otherNavProperty.FromEndMember.Name).FirstOrDefault().Value; //[otherNavProperty.FromEndMember];

                        var left  = leftKeyMappings.Where(km => km.Key.Name == "PersonID");
                        var right = rightType.KeyMembers.Select(m => "\"" + rightKeyMappings.Where(km => km.Key.Name == m.Name).FirstOrDefault().Value + "\"").FirstOrDefault();
                    }

                    //Dual OrderBy to bring Keys to top of list
                    //Iterate all properties for this particular Entity.
                    var properties = entityset.ElementType.Properties.OrderBy(s => s.Name).OrderBy(p => entityset.ElementType.KeyMembers.Contains(p) == false).ToArray();
                    foreach (var property in properties)
                    {
                        var propertyname = property.Name;

                        //This did not work in the T4 Template.
                        var mapping1 = mlr.PropertyToColumnMapping[entityset.ElementType];

                        //PropertyToColumnMapping is a collection for ALL Entities, so here the particular Entity needs to be filtered out.
                        //Mapping returned is a complex generic Dictionary.
                        var mapping2 = mlr.PropertyToColumnMapping.Where(k => k.Key == entityset.ElementType).FirstOrDefault().Value;
                        var mapping3 = mlr.PropertyToColumnMapping.Where(k => k.Key.FullName == entityset.ElementType.FullName).FirstOrDefault().Value;

                        var mapping4 = mapping3.Item2.Where(p => p.Key.Name == property.Name).FirstOrDefault().Value;

                        var i1       = mapping1.Item1;
                        var i2       = mapping1.Item2;
                        var mapright = i2[property];
                    }
                }

                //********************************************************************************

                //Demo 2
                //This takes EF.Utility.CS.ttinclude and receates as
                //.net Classes.
                //
                MyTextTransformation tt   = new MyTextTransformation();
                CodeGenerationTools  code = new CodeGenerationTools(tt);

                CodeRegion     cregion = new CodeRegion(tt, 1);
                MetadataTools  mtool   = new MetadataTools(tt);
                MetadataLoader mloader = new MetadataLoader(tt);

                var ItemCollection = mloader.CreateEdmItemCollection(inputFile);

                var Container = ItemCollection.GetItems <EntityContainer>()[0];
                Console.WriteLine(String.Format("Container Name: {0}", Container.Name));
                Console.WriteLine(String.Format("Model Namespace: {0}", mloader.GetModelNamespace(inputFile)));
                Console.WriteLine(String.Format("No Of Items in ItemsCollection: {0}\n", ItemCollection.Count));
                Console.WriteLine("Press any key to continue.\n"); Console.ReadKey();

                foreach (var i in ItemCollection)
                {
                    Console.WriteLine(String.Format("Item: {0}, {1}", i.ToString(), i.BuiltInTypeKind.ToString()));
                }
                Console.WriteLine("Press any key to continue.\n"); Console.ReadKey();

                EdmItemCollection edmItemCollection = null;;
                var ret = mloader.TryCreateEdmItemCollection(inputFile, out edmItemCollection);

                StoreItemCollection storeItemCollection = null;
                ret = mloader.TryCreateStoreItemCollection(inputFile, out storeItemCollection);

                StorageMappingItemCollection storageMappingItemCollection = null;
                ret = mloader.TryCreateStorageMappingItemCollection(inputFile, edmItemCollection, storeItemCollection, out storageMappingItemCollection);
                foreach (var i in storageMappingItemCollection)
                {
                    Console.WriteLine(String.Format("Item: {0}, {1}", i.ToString(), i.BuiltInTypeKind.ToString()));
                }
                DataSpace ds = storageMappingItemCollection.DataSpace;

                MetadataWorkspace metadataWorkspace = null;
                ret = mloader.TryLoadAllMetadata(inputFile, out metadataWorkspace);

                //Get the schema "dbo" from a particular Entity.
                EntityContainer ec          = storeItemCollection.GetItems <EntityContainer>().First();
                EntitySet       eset        = ec.GetEntitySetByName(code.Escape("People"), true);
                string          schemaName1 = eset.MetadataProperties["Schema"].Value.ToString();

                //Get the schema "dbo" from any Entity. I guess the schema will be same for all?!
                EntitySetBase fes         = ec.BaseEntitySets.FirstOrDefault();
                string        schemaName2 = fes.MetadataProperties["Schema"].Value.ToString();

                var edmxSchema = EDMXchema.GetSchemaElement(inputFile);

                Console.WriteLine("Press any key to continue.\n"); Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine("Press any key to quit.");
            Console.ReadKey();

            // var loadResult = LoadMetadata(inputFile);
        }
示例#28
0
        public bool IsInitialized(StoreItemCollection edmStoreSchema)
        {
            // TODO: Lock
            if (this.database == null)
            {
                return false;
            }

            // Find container
            EntityContainer entityContainer = edmStoreSchema.GetItems<EntityContainer>().FirstOrDefault();

            foreach (EntitySet entitySet in entityContainer.BaseEntitySets.OfType<EntitySet>())
            {
                // TODO: Verify fields
                if (!this.Internal.ContainsTable(entitySet.GetTableName()))
                {
                    return false;
                }
            }

            return true;
        }
        protected override string DbCreateDatabaseScript(string providerManifestToken,
        StoreItemCollection storeItemCollection)
        {
            StringBuilder sql = new StringBuilder();

              sql.AppendLine("-- MySql script");
              sql.AppendLine("-- Created on " + DateTime.Now);

              if (serverVersion == null)
            serverVersion = new Version(providerManifestToken == null ? "5.5" : providerManifestToken);

              foreach (EntityContainer container in storeItemCollection.GetItems<EntityContainer>())
              {
            // now output the tables
            foreach (EntitySet es in container.BaseEntitySets.OfType<EntitySet>())
            {
              sql.Append(GetTableCreateScript(es));
            }

            // now output the foreign keys
            foreach (AssociationSet a in container.BaseEntitySets.OfType<AssociationSet>())
            {
              sql.Append(GetAssociationCreateScript(a.ElementType));
            }
              }

              return sql.ToString();
        }