示例#1
0
        public IEntityMap <TEntity> Build()
        {
            var entityType = new SchemaEntityType(typeof(TEntity), typeof(TSchema), _entityTypeSelector);

            var entityFactory = new DynamicEntityFactory <TEntity>(ImplementationType, entityType);

            return(new DynamicEntityMap <TEntity, TSchema>(entityType, entityFactory, _properties, _sliceProviders));
        }
        private static void LoadEntityTypePhase2(
            SchemaEntityType element,
            DbProviderManifest providerManifest,
            Converter.ConversionCache convertedItemCache,
            Dictionary <SchemaElement, GlobalItem> newGlobalItems)
        {
            EntityType newGlobalItem = (EntityType)newGlobalItems[(SchemaElement)element];

            foreach (System.Data.Entity.Core.SchemaObjectModel.NavigationProperty navigationProperty in element.NavigationProperties)
            {
                newGlobalItem.AddMember((EdmMember)Converter.ConvertToNavigationProperty(newGlobalItem, navigationProperty, providerManifest, convertedItemCache, newGlobalItems));
            }
        }
示例#3
0
        internal static Property GetProperty_Reccursive(SchemaEntityType entityType, string propertyName)
        {
            var property = entityType.Index_Properties_Name.GetValueOrNull(propertyName);

            if (property != null)
            {
                return(property);
            }
            if (entityType.BaseType != null)
            {
                return(GetProperty_Reccursive(entityType.BaseType, propertyName));
            }
            throw new Exception("Could not found the property.");
        }
示例#4
0
        /// <summary>Gets the entity.</summary>
        /// <typeparam name="T">Generic type parameter.</typeparam>
        /// <returns>A T.</returns>
        public SchemaEntityType <T> Entity <T>() where T : class
        {
            var type = typeof(T).Name;

            if (!ConceptualModel.Index_EntityTypes_Name.ContainsKey(type))
            {
                throw new InvalidOperationException(ExceptionMessage.GeneralException);
            }

            var conceptual      = ConceptualModel.Index_EntityTypes_Name[type];
            var entityContainer = new SchemaEntityType <T> {
                Info = conceptual
            };

            return(entityContainer);
        }
        private static EntityType ConvertToEntityType(
            SchemaEntityType element,
            DbProviderManifest providerManifest,
            Converter.ConversionCache convertedItemCache,
            Dictionary <SchemaElement, GlobalItem> newGlobalItems)
        {
            string[] strArray = (string[])null;
            if (element.DeclaredKeyProperties.Count != 0)
            {
                strArray = new string[element.DeclaredKeyProperties.Count];
                for (int index = 0; index < strArray.Length; ++index)
                {
                    strArray[index] = element.DeclaredKeyProperties[index].Property.Name;
                }
            }
            EdmProperty[] edmPropertyArray = new EdmProperty[element.Properties.Count];
            int           num = 0;

            foreach (StructuredProperty property in element.Properties)
            {
                edmPropertyArray[num++] = Converter.ConvertToProperty(property, providerManifest, convertedItemCache, newGlobalItems);
            }
            EntityType entityType = new EntityType(element.Name, element.Namespace, Converter.GetDataSpace(providerManifest), (IEnumerable <string>)strArray, (IEnumerable <EdmMember>)edmPropertyArray);

            if (element.BaseType != null)
            {
                entityType.BaseType = (EdmType)Converter.LoadSchemaElement((System.Data.Entity.Core.SchemaObjectModel.SchemaType)element.BaseType, providerManifest, convertedItemCache, newGlobalItems);
            }
            entityType.Abstract = element.IsAbstract;
            if (element.Documentation != null)
            {
                entityType.Documentation = Converter.ConvertToDocumentation(element.Documentation);
            }
            Converter.AddOtherContent((SchemaElement)element, (MetadataItem)entityType);
            newGlobalItems.Add((SchemaElement)element, (GlobalItem)entityType);
            return(entityType);
        }
 internal List <Tuple <string, object> > GetInnerValues <T>(IQueryable <T> query, Expression <Func <T, T> > updateFactory, SchemaEntityType <T> entity) where T : class
        /// <summary>Creates a command to execute the batch operation.</summary>
        /// <param name="query">The query.</param>
        /// <param name="entity">The schema entity.</param>
        /// <returns>The new command to execute the batch operation.</returns>
        internal DbCommand CreateCommand <T>(ObjectQuery query, SchemaEntityType <T> entity, List <Tuple <string, object> > values)
        {
            var  command      = query.Context.CreateStoreCommand();
            bool isMySql      = command.GetType().FullName.Contains("MySql");
            var  isSqlCe      = command.GetType().Name == "SqlCeCommand";
            var  isOracle     = command.GetType().Namespace.Contains("Oracle");
            var  isPostgreSQL = command.GetType().Name == "NpgsqlCommand";

            // Oracle BindByName
            if (isOracle)
            {
                var bindByNameProperty = command.GetType().GetProperty("BindByName") ?? command.GetType().GetProperty("PassParametersByName");
                if (bindByNameProperty != null)
                {
                    bindByNameProperty.SetValue(command, true, null);
                }
            }

            // GET mapping
            var mapping = entity.Info.EntityTypeMapping.MappingFragment;
            var store   = mapping.StoreEntitySet;

            string tableName;

            if (isMySql)
            {
                tableName = string.Concat("`", store.Table, "`");
            }
            else if (isSqlCe)
            {
                tableName = string.Concat("[", store.Table, "]");
            }
            else if (isOracle)
            {
                tableName = string.IsNullOrEmpty(store.Schema) || store.Schema == "dbo" ?
                            string.Concat("\"", store.Table, "\"") :
                            string.Concat("\"", store.Schema, "\".\"", store.Table, "\"");
            }
            else if (isPostgreSQL)
            {
                tableName = string.IsNullOrEmpty(store.Schema) ?
                            string.Concat("\"", store.Table, "\"") :
                            string.Concat("\"", store.Schema, "\".\"", store.Table, "\"");
            }
            else
            {
                tableName = string.IsNullOrEmpty(store.Schema) ?
                            string.Concat("[", store.Table, "]") :
                            string.Concat("[", store.Schema, "].[", store.Table, "]");
            }


            // GET keys mappings
            var columnKeys = new List <string>();

            foreach (var propertyKey in entity.Info.Key.PropertyRefs)
            {
                var mappingProperty = mapping.ScalarProperties.Find(x => x.Name == propertyKey.Name);

                if (mappingProperty == null)
                {
                    throw new Exception(string.Format(ExceptionMessage.BatchOperations_PropertyNotFound, propertyKey.Name));
                }

                columnKeys.Add(mappingProperty.ColumnName);
            }


            // GET command text template
            var commandTextTemplate =
#if TODO
                BatchSize > 0 ?
                BatchDelayInterval > 0 ?
                CommandTextWhileDelayTemplate :
                CommandTextWhileTemplate :
#endif
                isPostgreSQL ? CommandTextTemplate_PostgreSQL :
                isOracle ? CommandTextOracleTemplate :
                isMySql ? CommandTextTemplate_MySQL :
                isSqlCe ? CommandTextTemplateSqlCe :
                CommandTextTemplate;

            // GET inner query
            var customQuery = query.GetCommandTextAndParameters();

            if (customQuery.Item1.EndsWith("WHERE 1 = 0", StringComparison.InvariantCultureIgnoreCase))
            {
                return(null);
            }

            var querySelect = customQuery.Item1;

            // GET primary key join
            string primaryKeys;
            string setValues;

            if (isSqlCe)
            {
                primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat(tableName + ".", EscapeName(x, isMySql, isOracle, isPostgreSQL), " = B.", EscapeName(x, isMySql, isOracle, isPostgreSQL), "")));

                setValues = string.Join("," + Environment.NewLine, values.Select((x, i) => x.Item2 is ConstantExpression ?
                                                                                 string.Concat(EscapeName(x.Item1, isMySql, isOracle, isPostgreSQL), " = ", ((ConstantExpression)x.Item2).Value.ToString().Replace("B.[", "[")) :
                                                                                 string.Concat(EscapeName(x.Item1, isMySql, isOracle, isPostgreSQL), " = @zzz_BatchUpdate_", i)));
            }
            else if (isOracle || isPostgreSQL)
            {
                primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat(tableName + ".", EscapeName(x, isMySql, isOracle, isPostgreSQL), " = B.", EscapeName(x, isMySql, isOracle, isPostgreSQL), "")));

                // GET updateSetValues
                setValues = string.Join("," + Environment.NewLine, values.Select((x, i) => x.Item2 is ConstantExpression ?
                                                                                 string.Concat(EscapeName(x.Item1, isMySql, isOracle, isPostgreSQL), " = ", ((ConstantExpression)x.Item2).Value) :
                                                                                 string.Concat(EscapeName(x.Item1, isMySql, isOracle, isPostgreSQL), " = :zzz_BatchUpdate_", i)));
            }
            else
            {
                primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.", EscapeName(x, isMySql, isOracle, isPostgreSQL), " = B.", EscapeName(x, isMySql, isOracle, isPostgreSQL), "")));

                // GET updateSetValues
                setValues = string.Join("," + Environment.NewLine, values.Select((x, i) => x.Item2 is ConstantExpression ?
                                                                                 string.Concat("A.", EscapeName(x.Item1, isMySql, isOracle, isPostgreSQL), " = ", ((ConstantExpression)x.Item2).Value) :
                                                                                 string.Concat("A.", EscapeName(x.Item1, isMySql, isOracle, isPostgreSQL), " = @zzz_BatchUpdate_", i)));
            }

            // REPLACE template
            commandTextTemplate = commandTextTemplate.Replace("{TableName}", tableName)
                                  .Replace("{Select}", querySelect)
                                  .Replace("{PrimaryKeys}", primaryKeys)
                                  .Replace("{SetValue}", setValues);

            // CREATE command
            command.CommandText = commandTextTemplate;

            // ADD Parameter
            var parameterCollection = customQuery.Item2;

#if EF5
            foreach (ObjectParameter parameter in parameterCollection)
            {
                var param = command.CreateParameter();
                param.CopyFrom(parameter);

                command.Parameters.Add(param);
            }
#elif EF6
            foreach (DbParameter parameter in parameterCollection)
            {
                var param = command.CreateParameter();
                param.CopyFrom(parameter);

                command.Parameters.Add(param);
            }
#endif

            for (var i = 0; i < values.Count; i++)
            {
                var value = values[i];

                if (value.Item2 is ConstantExpression)
                {
                    continue;
                }

                var parameterPrefix = isOracle ? ":" : "@";

                var parameter = command.CreateParameter();
                parameter.ParameterName = parameterPrefix + "zzz_BatchUpdate_" + i;
                parameter.Value         = values[i].Item2 ?? DBNull.Value;
                command.Parameters.Add(parameter);
            }

            return(command);
        }
        /// <summary>Creates a command to execute the batch operation.</summary>
        /// <param name="query">The query.</param>
        /// <param name="entity">The schema entity.</param>
        /// <returns>The new command to execute the batch operation.</returns>
        internal DbCommand CreateCommand <T>(ObjectQuery query, SchemaEntityType <T> entity)
        {
            // GET mapping
            var mapping   = entity.Info.EntityTypeMapping.MappingFragment;
            var store     = mapping.StoreEntitySet;
            var tableName = string.IsNullOrEmpty(store.Schema) ?
                            string.Concat("[", store.Table, "]") :
                            string.Concat("[", store.Schema, "].[", store.Table, "]");

            // GET keys mappings
            var columnKeys = new List <string>();

            foreach (var propertyKey in entity.Info.Key.PropertyRefs)
            {
                var mappingProperty = mapping.ScalarProperties.Find(x => x.Name == propertyKey.Name);

                if (mappingProperty == null)
                {
                    throw new Exception(string.Format(ExceptionMessage.BatchOperations_PropertyNotFound, propertyKey.Name));
                }

                columnKeys.Add(mappingProperty.ColumnName);
            }

            // GET command text template
            var commandTextTemplate = BatchSize > 0 ?
                                      BatchDelayInterval > 0 ?
                                      CommandTextWhileDelayTemplate :
                                      CommandTextWhileTemplate :
                                      CommandTextTemplate;

            // GET inner query
            var querySelect = query.ToTraceString();

            // GET primary key join
            var primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.[", x, "] = B.[", x, "]")));

            // REPLACE template
            commandTextTemplate = commandTextTemplate.Replace("{TableName}", tableName)
                                  .Replace("{Select}", querySelect)
                                  .Replace("{PrimaryKeys}", primaryKeys)
                                  .Replace("{Top}", BatchSize.ToString())
                                  .Replace("{Delay}", TimeSpan.FromMilliseconds(BatchDelayInterval).ToString(@"hh\:mm\:ss\:fff"));

            // CREATE command
            var command = query.Context.CreateStoreCommand();

            command.CommandText = commandTextTemplate;

            // ADD Parameter
            var parameterCollection = query.Parameters;

            foreach (var parameter in parameterCollection)
            {
                var param = command.CreateParameter();
                param.ParameterName = parameter.Name;
                param.Value         = parameter.Value;

                command.Parameters.Add(param);
            }

            return(command);
        }
示例#9
0
        /// <summary>Creates a command to execute the batch operation.</summary>
        /// <param name="query">The query.</param>
        /// <param name="entity">The schema entity.</param>
        /// <returns>The new command to execute the batch operation.</returns>
        internal DbCommand CreateCommand <T>(ObjectQuery query, SchemaEntityType <T> entity, List <Tuple <string, object> > values)
        {
            var  command = query.Context.CreateStoreCommand();
            bool isMySql = command.GetType().FullName.Contains("MySql");

            // GET mapping
            var mapping = entity.Info.EntityTypeMapping.MappingFragment;
            var store   = mapping.StoreEntitySet;

            string tableName;

            if (isMySql)
            {
                tableName = string.Concat("`", store.Table, "`");
            }
            else
            {
                tableName = string.IsNullOrEmpty(store.Schema) ?
                            string.Concat("[", store.Table, "]") :
                            string.Concat("[", store.Schema, "].[", store.Table, "]");
            }


            // GET keys mappings
            var columnKeys = new List <string>();

            foreach (var propertyKey in entity.Info.Key.PropertyRefs)
            {
                var mappingProperty = mapping.ScalarProperties.Find(x => x.Name == propertyKey.Name);

                if (mappingProperty == null)
                {
                    throw new Exception(string.Format(ExceptionMessage.BatchOperations_PropertyNotFound, propertyKey.Name));
                }

                columnKeys.Add(mappingProperty.ColumnName);
            }


            // GET command text template
            var commandTextTemplate =
#if TODO
                BatchSize > 0 ?
                BatchDelayInterval > 0 ?
                CommandTextWhileDelayTemplate :
                CommandTextWhileTemplate :
#endif
                isMySql ? CommandTextTemplate_MySQL : CommandTextTemplate;

            // GET inner query
            var querySelect = query.ToTraceString();

            // GET primary key join
            var primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.", EscapeName(x, isMySql), " = B.", EscapeName(x, isMySql), "")));

            // GET updateSetValues
            var setValues = string.Join("," + Environment.NewLine, values.Select((x, i) => x.Item2 is ConstantExpression ?
                                                                                 string.Concat("A.", EscapeName(x.Item1, isMySql), " = ", ((ConstantExpression)x.Item2).Value) :
                                                                                 string.Concat("A.", EscapeName(x.Item1, isMySql), " = @zzz_BatchUpdate_", i)));

            // REPLACE template
            commandTextTemplate = commandTextTemplate.Replace("{TableName}", tableName)
                                  .Replace("{Select}", querySelect)
                                  .Replace("{PrimaryKeys}", primaryKeys)
                                  .Replace("{SetValue}", setValues);

            // CREATE command
            command.CommandText = commandTextTemplate;

            // ADD Parameter
            var parameterCollection = query.Parameters;

            foreach (var parameter in parameterCollection)
            {
                var param = command.CreateParameter();
                param.ParameterName = parameter.Name;
                param.Value         = parameter.Value;

                command.Parameters.Add(param);
            }

            for (var i = 0; i < values.Count; i++)
            {
                var value = values[i];

                if (value.Item2 is ConstantExpression)
                {
                    continue;
                }

                var parameter = command.CreateParameter();
                parameter.ParameterName = "@zzz_BatchUpdate_" + i;
                parameter.Value         = values[i].Item2 ?? DBNull.Value;
                command.Parameters.Add(parameter);
            }

            return(command);
        }
        /// <summary>Creates a command to execute the batch operation.</summary>
        /// <exception cref="Exception">Thrown when an exception error condition occurs.</exception>
        /// <typeparam name="T">Generic type parameter.</typeparam>
        /// <param name="query">The query.</param>
        /// <param name="entity">The schema entity.</param>
        /// <param name="visitor">The visitor.</param>
        /// <returns>The new command to execute the batch operation.</returns>
        internal DbCommand CreateCommand <T>(ObjectQuery query, SchemaEntityType <T> entity)
        {
            // GET command
            var command = query.Context.CreateStoreCommand();

            bool isMySql  = command.GetType().FullName.Contains("MySql");
            var  isSqlCe  = command.GetType().Name == "SqlCeCommand";
            var  isOracle = command.GetType().Namespace.Contains("Oracle");

            // Oracle BindByName
            if (isOracle)
            {
                var bindByNameProperty = command.GetType().GetProperty("BindByName") ?? command.GetType().GetProperty("PassParametersByName");
                if (bindByNameProperty != null)
                {
                    bindByNameProperty.SetValue(command, true, null);
                }
            }

            // GET mapping
            var mapping = entity.Info.EntityTypeMapping.MappingFragment;
            var store   = mapping.StoreEntitySet;

            string tableName;

            if (isMySql)
            {
                tableName = string.Concat("`", store.Table, "`");
            }
            else if (isSqlCe)
            {
                tableName = string.Concat("[", store.Table, "]");
            }
            else if (isOracle)
            {
                tableName = string.IsNullOrEmpty(store.Schema) || store.Schema == "dbo" ?
                            string.Concat("\"", store.Table, "\"") :
                            string.Concat("\"", store.Schema, "\".\"", store.Table, "\"");
            }
            else
            {
                tableName = string.IsNullOrEmpty(store.Schema) ?
                            string.Concat("[", store.Table, "]") :
                            string.Concat("[", store.Schema, "].[", store.Table, "]");
            }

            // GET keys mappings
            var columnKeys = new List <string>();

            foreach (var propertyKey in entity.Info.Key.PropertyRefs)
            {
                var mappingProperty = mapping.ScalarProperties.Find(x => x.Name == propertyKey.Name);

                if (mappingProperty == null)
                {
                    throw new Exception(string.Format(ExceptionMessage.BatchOperations_PropertyNotFound, propertyKey.Name));
                }

                columnKeys.Add(mappingProperty.ColumnName);
            }

            // GET command text template
            var commandTextTemplate = command.GetType().Name == "NpgsqlCommand" ?
                                      CommandTextPostgreSQLTemplate :
                                      isOracle ?
                                      CommandTextOracleTemplate :
                                      isMySql ?
                                      CommandTextTemplate_MySql :
                                      isSqlCe ?
                                      CommandTextSqlCeTemplate :
                                      BatchSize > 0 ?
                                      BatchDelayInterval > 0 ?
                                      CommandTextWhileDelayTemplate :
                                      CommandTextWhileTemplate :
                                      CommandTextTemplate;

            // GET inner query
            var customQuery = query.GetCommandTextAndParameters();
            var querySelect = customQuery.Item1;

            // GET primary key join
            string primaryKeys;

            if (isSqlCe || isOracle)
            {
                primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat(tableName + ".", EscapeName(x, isMySql, isOracle), " = B.", EscapeName(x, isMySql, isOracle), "")));
            }
            else
            {
                primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.", EscapeName(x, isMySql, isOracle), " = B.", EscapeName(x, isMySql, isOracle), "")));
            }

            // REPLACE template
            commandTextTemplate = commandTextTemplate.Replace("{TableName}", tableName)
                                  .Replace("{Select}", querySelect)
                                  .Replace("{PrimaryKeys}", primaryKeys)
                                  .Replace("{Top}", BatchSize.ToString())
                                  .Replace("{Delay}", TimeSpan.FromMilliseconds(BatchDelayInterval).ToString(@"hh\:mm\:ss\:fff"));

            // CREATE command
            command.CommandText = commandTextTemplate;

            // ADD Parameter
            var parameterCollection = customQuery.Item2;

#if EF5
            foreach (ObjectParameter parameter in parameterCollection)
            {
                var param = command.CreateParameter();
                param.ParameterName = parameter.Name;
                param.Value         = parameter.Value ?? DBNull.Value;

                command.Parameters.Add(param);
            }
#elif EF6
            foreach (DbParameter parameter in parameterCollection)
            {
                var param = command.CreateParameter();
                param.ParameterName = parameter.ParameterName;
                param.Value         = parameter.Value ?? DBNull.Value;

                command.Parameters.Add(param);
            }
#endif

            return(command);
        }
示例#11
0
        private static IEnumerable <TableDefinition> GetTableDefinitions(DbModelPlus model, string strName)
        {
            //get our entity type
            SchemaEntityType setEntityType = model.ConceptualModel.Index_EntityTypes_Name[strName];

            //create our update entity
            TableDefinition ueEntity = new TableDefinition();

            //create our return list and add our definition
            List <TableDefinition> lsTableDefinitions = new List <TableDefinition>();

            //if we have mapping data, leverage it
            if (setEntityType.EntityTypeMapping != null)
            {
                lsTableDefinitions.Add(ueEntity);

                ueEntity.Schema = setEntityType.EntityTypeMapping.MappingFragment.StoreEntitySet.Schema;
                ueEntity.Table  = setEntityType.EntityTypeMapping.MappingFragment.StoreEntitySet.Table;

                //map our keys for this model
                List <ScalarPropertyMapping> lsKeys = new List <ScalarPropertyMapping>();
                foreach (PropertyRefElement propertyKey in setEntityType.EntityTypeMapping.MappingFragment.StoreEntitySet.EntityType.Key.PropertyRefs)
                {
                    ScalarPropertyMapping mappingProperty = setEntityType.EntityTypeMapping.MappingFragment.ScalarProperties.Find(x => x.Name == propertyKey.Name);

                    if (mappingProperty == null)
                    {
                        throw new Exception(string.Format(ExceptionMessage.BatchOperations_PropertyNotFound, propertyKey.Name));
                    }

                    lsKeys.Add(mappingProperty);
                }
                ueEntity.Keys = lsKeys;

                //clone our list of properties
                ueEntity.Properties = setEntityType.EntityTypeMapping.MappingFragment.ScalarProperties.ToList();

                //if there's no base type, stop here
                if (string.IsNullOrEmpty(setEntityType.BaseType))
                {
                    return(lsTableDefinitions);
                }
            }

            //stop here if there's no base type
            if (string.IsNullOrEmpty(setEntityType.BaseType))
            {
                return(lsTableDefinitions);
            }

            //strip the alias bit
            string strBaseType = setEntityType.BaseType.Replace(model.ConceptualModel.Alias + ".", "");

            //get the columns for our base class
            IEnumerable <TableDefinition> lsBaseTableDefinitions = GetTableDefinitions(model, strBaseType);

            //increment the order of the base column entities by one
            foreach (TableDefinition ueBaseEntity in lsBaseTableDefinitions)
            {
                ueBaseEntity.Order += 1;

                lsTableDefinitions.Add(ueBaseEntity);
            }

            return(lsTableDefinitions);
        }