Example #1
0
        public void Generate(EntityType entityType, DbDatabaseMapping databaseMapping)
        {
            if (entityType.Abstract)
            {
                return;
            }
            EntitySet                   entitySet        = databaseMapping.Model.GetEntitySet(entityType);
            EntitySetMapping            entitySetMapping = databaseMapping.GetEntitySetMapping(entitySet);
            List <ColumnMappingBuilder> list1            = ModificationFunctionMappingGenerator.GetColumnMappings(entityType, entitySetMapping).ToList <ColumnMappingBuilder>();
            List <Tuple <ModificationFunctionMemberPath, EdmProperty> > list2 = ModificationFunctionMappingGenerator.GetIndependentFkColumns(entityType, databaseMapping).ToList <Tuple <ModificationFunctionMemberPath, EdmProperty> >();
            ModificationFunctionMapping functionMapping1 = this.GenerateFunctionMapping(ModificationOperator.Insert, (EntitySetBase)entitySetMapping.EntitySet, (EntityTypeBase)entityType, databaseMapping, (IEnumerable <EdmProperty>)entityType.Properties, (IEnumerable <Tuple <ModificationFunctionMemberPath, EdmProperty> >)list2, (IList <ColumnMappingBuilder>)list1, entityType.Properties.Where <EdmProperty>((Func <EdmProperty, bool>)(p => p.HasStoreGeneratedPattern())), (string)null);
            ModificationFunctionMapping functionMapping2 = this.GenerateFunctionMapping(ModificationOperator.Update, (EntitySetBase)entitySetMapping.EntitySet, (EntityTypeBase)entityType, databaseMapping, (IEnumerable <EdmProperty>)entityType.Properties, (IEnumerable <Tuple <ModificationFunctionMemberPath, EdmProperty> >)list2, (IList <ColumnMappingBuilder>)list1, entityType.Properties.Where <EdmProperty>((Func <EdmProperty, bool>)(p =>
            {
                StoreGeneratedPattern?generatedPattern = p.GetStoreGeneratedPattern();
                if (generatedPattern.GetValueOrDefault() == StoreGeneratedPattern.Computed)
                {
                    return(generatedPattern.HasValue);
                }
                return(false);
            })), (string)null);
            ModificationFunctionMapping           functionMapping3            = this.GenerateFunctionMapping(ModificationOperator.Delete, (EntitySetBase)entitySetMapping.EntitySet, (EntityTypeBase)entityType, databaseMapping, (IEnumerable <EdmProperty>)entityType.Properties, (IEnumerable <Tuple <ModificationFunctionMemberPath, EdmProperty> >)list2, (IList <ColumnMappingBuilder>)list1, (IEnumerable <EdmProperty>)null, (string)null);
            EntityTypeModificationFunctionMapping modificationFunctionMapping = new EntityTypeModificationFunctionMapping(entityType, functionMapping3, functionMapping1, functionMapping2);

            entitySetMapping.AddModificationFunctionMapping(modificationFunctionMapping);
        }
        private static void SetProperties(EntityMap entityMap, EntitySetMapping mapping, Type type)
        {
            var isTypeOf = new HashSet <string>(GetParentTypes(type).Union(new[] { type }).Select(o => o.Name));

            foreach (var propertyMapping in
                     mapping.EntityTypeMappings.Where(
                         o => o.EntityTypes == null || o.EntityTypes.Count < 1 ||
                         o.EntityTypes.Any(et => isTypeOf.Contains(et.Name)))
                     .SelectMany(o => o.Fragments)
                     .SelectMany(o => o.PropertyMappings)
                     //.Where(o => o.Property.DeclaringType.)
                     .GroupBy(o => o.Property.Name).Select(o => o.First()))
            {
                var map = new PropertyMap
                {
                    PropertyName = propertyMapping.Property.Name
                };

                entityMap.PropertyMaps.Add(map);

                var scalarPropertyMapping = propertyMapping as ScalarPropertyMapping;
                if (scalarPropertyMapping != null)
                {
                    map.ColumnName = scalarPropertyMapping.Column.Name;
                    continue;
                }

                // TODO support complex mapping
                var complexPropertyMapping = propertyMapping as ComplexPropertyMapping;
            }
        }
        private static void SetProperties(EntityMap entityMap, EntitySetMapping mapping, Type type)
        {
            var modelTypeKeyMembers = entityMap.ModelType.KeyMembers.ToArray();
            var isTypeOf            = new HashSet <string>(GetParentTypes(type).Union(new[] { type }).Select(o => o.Name), StringComparer.Ordinal);

            foreach (var propertyMapping in mapping.EntityTypeMappings.Where(
                         o => o.EntityTypes == null || o.EntityTypes.Count < 1 || o.EntityTypes.Any(et => isTypeOf.Contains(et.Name)))
                     .SelectMany(o => o.Fragments)
                     .SelectMany(o => o.PropertyMappings)
                     //.Where(o => o.Property.DeclaringType)
                     .GroupBy(o => o.Property.Name).Select(o => o.First()))
            {
                var map = new PropertyMap
                {
                    PropertyName = propertyMapping.Property.Name,
                    IsKey        = modelTypeKeyMembers.Any(km => km.Name.Equals(propertyMapping.Property.Name, StringComparison.Ordinal))
                };

                if (propertyMapping is ScalarPropertyMapping)
                {
                    map.ColumnName = ((ScalarPropertyMapping)propertyMapping).Column.Name;
                }
                //else if (propertyMapping is ConditionPropertyMapping)
                //{
                //	map.ColumnName = ((ConditionPropertyMapping)propertyMapping).Column.Name;
                //}
                //else if (propertyMapping is ComplexPropertyMapping)
                //{
                //}

                entityMap.PropertyMaps.Add(map);
            }
        }
Example #4
0
        private TypeCacheEntry GetCacheEntry(Type t, EntitySetMapping mapping)
        {
            if (!_typesCache.ContainsKey(t))
            {
                lock (_typesCacheLocker)
                {
                    if (!_typesCache.ContainsKey(t))
                    {
                        if (mapping == null)
                        {
                            return(null);
                        }
                        // Find the storage entity set (table) that the entity is mapped
                        var tableEntitySet = mapping
                                             .EntityTypeMappings.Single()
                                             .Fragments.Single()
                                             .StoreEntitySet;

                        // Return the table name from the storage entity set
                        var tableName = tableEntitySet.MetadataProperties["Table"].Value ?? tableEntitySet.Name;
                        _typesCache[t] = new TypeCacheEntry()
                        {
                            TableName = tableName.ToString()
                        };
                    }
                }
            }
            return(_typesCache[t]);
        }
        protected override void InvokeInternal(CommandProcessorContext cpc)
        {
            // if don't have an ECM yet, go create one
            if (_entityContainerMapping == null)
            {
                var cmd = new CreateEntityContainerMappingCommand(_entitySet.Artifact);
                CommandProcessor.InvokeSingleCommand(cpc, cmd);

                _entityContainerMapping = cmd.EntityContainerMapping;
            }

            Debug.Assert(_entityContainerMapping != null, "_entityContainerMapping should not be null");
            if (_entityContainerMapping == null)
            {
                throw new CannotLocateParentItemException();
            }

            // create the ESM
            var esm = new EntitySetMapping(_entityContainerMapping, null);

            esm.Name.SetRefName(_entitySet);
            _entityContainerMapping.AddEntitySetMapping(esm);

            XmlModelHelper.NormalizeAndResolve(esm);

            _created = esm;
        }
        public static void SyncNullabilityCSSpace(
            this ColumnMappingBuilder propertyMappingBuilder,
            DbDatabaseMapping databaseMapping,
            IEnumerable <EntitySet> entitySets,
            EntityType toTable)
        {
            DebugCheck.NotNull(propertyMappingBuilder);

            var property = propertyMappingBuilder.PropertyPath.Last();

            EntitySetMapping setMapping = null;

            var baseType = (EntityType)property.DeclaringType.BaseType;

            if (baseType != null)
            {
                setMapping = GetEntitySetMapping(databaseMapping, baseType, entitySets);
            }

            while (baseType != null)
            {
                if (toTable == setMapping.EntityTypeMappings.First(m => m.EntityType == baseType).GetPrimaryTable())
                {
                    // CodePlex 2254: If current table is part of TPH mapping below the TPT mapping we are processing, then
                    // don't change the nullability because the TPH nullability calculated previously is still correct.
                    return;
                }

                baseType = (EntityType)baseType.BaseType;
            }

            propertyMappingBuilder.ColumnProperty.Nullable = property.Nullable;
        }
Example #7
0
        public static void RemoveDefaultDiscriminator(
            this MappingFragment entityTypeMappingFragment, EntitySetMapping entitySetMapping)
        {
            DebugCheck.NotNull(entityTypeMappingFragment);

            var discriminatorColumn = entityTypeMappingFragment.RemoveDefaultDiscriminatorCondition();

            if (discriminatorColumn != null)
            {
                var table = entityTypeMappingFragment.Table;

                table.Properties
                .Where(c => c.Name.Equals(discriminatorColumn.Name, StringComparison.Ordinal))
                .ToList()
                .Each(table.RemoveMember);
            }

            if (entitySetMapping != null &&
                entityTypeMappingFragment.IsConditionOnlyFragment()
                &&
                !entityTypeMappingFragment.ColumnConditions.Any())
            {
                var entityTypeMapping =
                    entitySetMapping.EntityTypeMappings.Single(
                        etm => etm.MappingFragments.Contains(entityTypeMappingFragment));

                entityTypeMapping.RemoveFragment(entityTypeMappingFragment);

                if (entityTypeMapping.MappingFragments.Count == 0)
                {
                    entitySetMapping.RemoveTypeMapping(entityTypeMapping);
                }
            }
        }
Example #8
0
        private static EntitySet GetTable(Type type, DbContext context)
        {
            EntitySet         table    = null;
            MetadataWorkspace metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace;

            // Get the part of the model that contains info about the actual CLR types
            ObjectItemCollection objectItemCollection = (ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace);

            // Get the entity type from the model that maps to the CLR type
            EntityType entityType = metadata.GetItems <EntityType>(DataSpace.OSpace)
                                    .SingleOrDefault(e => objectItemCollection.GetClrType(e) == type);

            if (entityType != null)
            {
                // Get the entity set that uses this entity type
                EntitySet entitySet = metadata.GetItems <EntityContainer>(DataSpace.CSpace)
                                      .SingleOrDefault()
                                      ?.EntitySets
                                      ?.SingleOrDefault(s => s.ElementType.Name == entityType.Name);

                if (entitySet != null)
                {
                    // Find the mapping between conceptual and storage model for this entity set
                    EntitySetMapping mapping = metadata.GetItems <EntityContainerMapping>(DataSpace.CSSpace)
                                               .SingleOrDefault()
                                               ?.EntitySetMappings
                                               ?.SingleOrDefault(s => s.EntitySet == entitySet);

                    // Find the storage entity set (table) that the entity is mapped
                    table = mapping?.EntityTypeMappings?.SelectMany(m => m.Fragments.Select(f => f.StoreEntitySet)).Distinct().FirstOrDefault();
                }
            }

            return(table);
        }
Example #9
0
        public void WriteMappingFragment_should_write_store_entity_set_name()
        {
            var fixture = new Fixture();

            var entityType      = new EntityType("E", "N", DataSpace.CSpace);
            var entitySet       = new EntitySet("ES", "S", null, null, entityType);
            var entityContainer = new EntityContainer("EC", DataSpace.SSpace);

            entityContainer.AddEntitySetBase(entitySet);

            var storageEntitySetMapping
                = new EntitySetMapping(
                      entitySet,
                      new EntityContainerMapping(entityContainer));

            TypeMapping typeMapping = new EntityTypeMapping(storageEntitySetMapping);

            var mappingFragment = new MappingFragment(entitySet, typeMapping, false);

            fixture.Writer.WriteMappingFragmentElement(mappingFragment);

            Assert.Equal(
                @"<MappingFragment StoreEntitySet=""ES"" />",
                fixture.ToString());
        }
Example #10
0
        /// <summary>
        /// Retrieves cached DB field name for property of particular type
        /// </summary>
        /// <param name="t">EF entity type</param>
        /// <param name="propertyName">Type's property name</param>
        /// <param name="mapping">Entity set maping (optional)</param>
        /// <returns>String field name. Table name has to be retrieved separately.  If null returned - please ty again specifying Mapping</returns>
        public string GetFieldName(Type t, string propertyName, EntitySetMapping mapping = null)
        {
            var entry = GetCacheEntry(t, mapping);

            if (entry == null)
            {
                return(null);
            }
            if (!entry.FieldNames.ContainsKey(propertyName))
            {
                if (mapping == null)
                {
                    return(null);
                }
                lock (entry._typeEntitiesLocker)
                {
                    if (!entry.FieldNames.ContainsKey(propertyName))
                    {
                        // Find the storage property (column) that the property is mapped
                        var columnName = mapping
                                         .EntityTypeMappings.Single()
                                         .Fragments.Single()
                                         .PropertyMappings
                                         .OfType <ScalarPropertyMapping>()
                                         .Single(m => m.Property.Name == propertyName)
                                         .Column
                                         .Name;
                        entry.FieldNames[propertyName] = columnName;
                    }
                }
            }
            return(entry.FieldNames[propertyName]);
        }
Example #11
0
        public void WriteEntitySetMappingElement(EntitySetMapping entitySetMapping)
        {
            DebugCheck.NotNull(entitySetMapping);

            _xmlWriter.WriteStartElement(MslConstructs.EntitySetMappingElement);
            _xmlWriter.WriteAttributeString(MslConstructs.EntitySetMappingNameAttribute, entitySetMapping.EntitySet.Name);

            foreach (var entityTypeMapping in entitySetMapping.EntityTypeMappings)
            {
                WriteEntityTypeMappingElement(entityTypeMapping);
            }

            foreach (var modificationFunctionMapping in entitySetMapping.ModificationFunctionMappings)
            {
                _xmlWriter.WriteStartElement(MslConstructs.EntityTypeMappingElement);
                _xmlWriter.WriteAttributeString(
                    MslConstructs.EntityTypeMappingTypeNameAttribute,
                    GetEntityTypeName(_entityTypeNamespace + "." + modificationFunctionMapping.EntityType.Name, false));

                WriteModificationFunctionMapping(modificationFunctionMapping);

                _xmlWriter.WriteEndElement();
            }

            _xmlWriter.WriteEndElement();
        }
Example #12
0
        private static EntitySetMapping GetMapping(DbContext context, Type t)
        {
            var objectContext        = ((IObjectContextAdapter)context).ObjectContext;
            var metadata             = objectContext.MetadataWorkspace;
            var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace));
            var entityType           = metadata.GetItems <EntityType>(DataSpace.OSpace)
                                       .FirstOrDefault(x => objectItemCollection.GetClrType(x) == t);

            if (entityType == null)
            {
                throw new Exception(string.Format("Type {0} does not belong to DbContext {1}", t.FullName, context.GetType().FullName));
            }

            var entitySet = metadata
                            .GetItems <EntityContainer>(DataSpace.CSpace)
                            .Single()
                            .EntitySets
                            .Single(s => s.ElementType.Name == entityType.Name);

            // Find the mapping between conceptual and storage model for this entity set
            EntitySetMapping mapping = metadata.GetItems <EntityContainerMapping>(DataSpace.CSSpace)
                                       .Single()
                                       .EntitySetMappings
                                       .Single(s => s.EntitySet == entitySet);

            return(mapping);
        }
 internal EntitySetTranslator(EntitySetMapping setMapping)
 {
     this.m_typeMappings = new Dictionary <EntityType, EntityTypeModificationFunctionMapping>();
     foreach (EntityTypeModificationFunctionMapping modificationFunctionMapping in setMapping.ModificationFunctionMappings)
     {
         this.m_typeMappings.Add(modificationFunctionMapping.EntityType, modificationFunctionMapping);
     }
 }
 internal static void AddRule(CommandProcessorContext cpc, EntitySetMapping element)
 {
     if (element != null)
     {
         IIntegrityCheck check = new EnforceEntitySetMappingRules(cpc, element);
         cpc.AddIntegrityCheck(check);
     }
 }
Example #15
0
        public static EntitySetMapping AddEntitySetMapping(
            this DbDatabaseMapping databaseMapping,
            EntitySet entitySet)
        {
            EntitySetMapping setMapping = new EntitySetMapping(entitySet, (EntityContainerMapping)null);

            databaseMapping.EntityContainerMappings.Single <EntityContainerMapping>().AddSetMapping(setMapping);
            return(setMapping);
        }
Example #16
0
 private static IEnumerable <ColumnMappingBuilder> GetColumnMappings(
     EntityType entityType,
     EntitySetMapping entitySetMapping)
 {
     return(((IEnumerable <EntityType>) new EntityType[1]
     {
         entityType
     }).Concat <EntityType>(ModificationFunctionMappingGenerator.GetParents(entityType)).SelectMany <EntityType, ColumnMappingBuilder>((Func <EntityType, IEnumerable <ColumnMappingBuilder> >)(et => entitySetMapping.TypeMappings.Where <TypeMapping>((Func <TypeMapping, bool>)(stm => stm.Types.Contains((EntityTypeBase)et))).SelectMany <TypeMapping, MappingFragment>((Func <TypeMapping, IEnumerable <MappingFragment> >)(stm => (IEnumerable <MappingFragment>)stm.MappingFragments)).SelectMany <MappingFragment, ColumnMappingBuilder>((Func <MappingFragment, IEnumerable <ColumnMappingBuilder> >)(mf => mf.ColumnMappings)))));
 }
Example #17
0
        /// <summary>
        /// Retrieves cached table name for type
        /// </summary>
        /// <param name="t">EF entity type</param>
        /// <param name="mapping">Entity set maping (optional)</param>
        /// <returns>String table name or null if not cached. If null returned - please ty again specifying Mapping</returns>
        public string GetTableName(Type t, EntitySetMapping mapping = null)
        {
            var entry = GetCacheEntry(t, mapping);

            if (entry == null)
            {
                return(null);
            }
            return(entry.TableName);
        }
        /// <summary>
        ///     Creates an EntityTypeMapping in the passed in EntitySetMapping, for the passed in type and kind.
        /// </summary>
        /// <param name="entitySetMapping">If this is null, then an EntitySetMapping will be created.</param>
        /// <param name="entityType">This must be a valid EntityType from the C-Model.</param>
        /// <param name="kind">Which kind of ETM to create.</param>
        internal CreateEntityTypeMappingCommand(
            EntitySetMapping entitySetMapping, ConceptualEntityType entityType, EntityTypeMappingKind kind)
        {
            CommandValidation.ValidateEntitySetMapping(entitySetMapping);
            CommandValidation.ValidateConceptualEntityType(entityType);

            _entitySetMapping = entitySetMapping;
            _entityType       = entityType;
            _kind             = kind;
        }
Example #19
0
        public TableMapping(List <ScalarPropertyMapping> columns, EntitySet entitySet, EntityType entityType, EntitySetMapping mapping)
        {
            var storeEntitySet = mapping.EntityTypeMappings.Single().Fragments.Single().StoreEntitySet;

            Columns    = columns;
            EntitySet  = entitySet;
            EntityType = entityType;
            Mapping    = mapping;
            Schema     = (string)storeEntitySet.MetadataProperties["Schema"].Value ?? storeEntitySet.Schema;
            TableName  = (string)storeEntitySet.MetadataProperties["Table"].Value ?? storeEntitySet.Name;
        }
        public static AssociationType ForeignKeyForNavigationProperty(this DbContext context, Type type, PropertyInfo navigationProperty)
        {
            MetadataWorkspace    metadata             = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace;
            ObjectItemCollection objectItemCollection = metadata.GetItemCollection(DataSpace.OSpace) as ObjectItemCollection;
            EntityType           entityType           = metadata.GetItems <EntityType>(DataSpace.OSpace).SingleOrDefault(e => objectItemCollection.GetClrType(e) == GetBaseTypeFor(type));
            EntitySet            entitySet            = metadata.GetItems <EntityContainer>(DataSpace.CSpace).Single().EntitySets.Single(s => s.ElementType.Name == entityType.Name);
            EntitySetMapping     mapping = metadata.GetItems <EntityContainerMapping>(DataSpace.CSSpace).Single().EntitySetMappings.Single(s => s.EntitySet == entitySet);
            string entityIdentity        = mapping.EntityTypeMappings.First().EntityType.ToString();

            entityType = metadata.GetItem <EntityType>(entityIdentity, DataSpace.CSpace);
            return(entityType.NavigationProperties.Single(p => p.Name.Equals(navigationProperty.Name)).ToEndMember.DeclaringType as AssociationType);
        }
Example #21
0
        BuildEntitySetMappings(EntityContainerMapping entityContainerMapping, SimpleMappingContext mappingContext)
        {
            Debug.Assert(entityContainerMapping != null, "entityContainerMapping != null");
            Debug.Assert(mappingContext != null, "mappingContext != null");

            foreach (var storeEntitySet in mappingContext.StoreEntitySets())
            {
                var entitySetMapping = new EntitySetMapping(mappingContext[storeEntitySet], entityContainerMapping);
                entitySetMapping.AddTypeMapping(BuildEntityTypeMapping(entitySetMapping, mappingContext, storeEntitySet));
                yield return(entitySetMapping);
            }
        }
            internal EntitySetTranslator(EntitySetMapping setMapping)
            {
                DebugCheck.NotNull(setMapping);
                DebugCheck.NotNull(setMapping.ModificationFunctionMappings);

                Debug.Assert(0 < setMapping.ModificationFunctionMappings.Count, "set mapping must exist and must specify function mappings");
                m_typeMappings = new Dictionary <EntityType, EntityTypeModificationFunctionMapping>();
                foreach (var typeMapping in setMapping.ModificationFunctionMappings)
                {
                    m_typeMappings.Add(typeMapping.EntityType, typeMapping);
                }
            }
            internal EntitySetTranslator(EntitySetMapping setMapping)
            {
                DebugCheck.NotNull(setMapping);
                DebugCheck.NotNull(setMapping.ModificationFunctionMappings);

                Debug.Assert(0 < setMapping.ModificationFunctionMappings.Count, "set mapping must exist and must specify function mappings");
                m_typeMappings = new Dictionary<EntityType, EntityTypeModificationFunctionMapping>();
                foreach (var typeMapping in setMapping.ModificationFunctionMappings)
                {
                    m_typeMappings.Add(typeMapping.EntityType, typeMapping);
                }
            }
        protected override void InvokeInternal(CommandProcessorContext cpc)
        {
            // make sure that there isn't an ETM of this kind already
            var entityTypeMapping = ModelHelper.FindEntityTypeMapping(cpc, _entityType, _kind, false);

            Debug.Assert(entityTypeMapping == null, "We are calling CreateEntityTypeMappingCommand and there is already one of this Kind");
            if (entityTypeMapping != null)
            {
                _created = entityTypeMapping;
                return;
            }

            // see if we can get the EntitySetMapping for our entity (if we weren't passed it)
            if (_entitySetMapping == null)
            {
                var ces = _entityType.EntitySet as ConceptualEntitySet;
                Debug.Assert(ces != null, "_entityType.EntitySet should be a ConceptualEntitySet");

                // find the EntitySetMapping for this type (V1 assumption is that there is only ESM per ES)
                EntitySetMapping esm = null;
                foreach (var depMapping in ces.GetAntiDependenciesOfType <EntitySetMapping>())
                {
                    esm = depMapping;
                    break;
                }

                _entitySetMapping = esm;
            }

            // if we still don't have an ESM, create one
            if (_entitySetMapping == null)
            {
                var cmd = new CreateEntitySetMappingCommand(
                    _entityType.Artifact.MappingModel().FirstEntityContainerMapping,
                    _entityType.EntitySet as ConceptualEntitySet);
                CommandProcessor.InvokeSingleCommand(cpc, cmd);
                _entitySetMapping = cmd.EntitySetMapping;
            }
            Debug.Assert(
                _entitySetMapping != null,
                "_entitySetMapping should not be null - we have been unable to find or create an EntitySetMapping");

            // create the ETM
            var etm = new EntityTypeMapping(_entitySetMapping, null, _kind);

            etm.TypeName.SetRefName(_entityType);
            _entitySetMapping.AddEntityTypeMapping(etm);

            XmlModelHelper.NormalizeAndResolve(etm);

            _created = etm;
        }
Example #25
0
 private static bool HasBaseWithIsTypeOf(
     EntitySetMapping entitySetMapping,
     EntityType entityType)
 {
     for (EdmType baseType = entityType.BaseType; baseType != null; baseType = baseType.BaseType)
     {
         if (entitySetMapping.EntityTypeMappings.Where <EntityTypeMapping>((Func <EntityTypeMapping, bool>)(etm => etm.EntityType == baseType)).Any <EntityTypeMapping>((Func <EntityTypeMapping, bool>)(etm => etm.IsHierarchyMapping)))
         {
             return(true);
         }
     }
     return(false);
 }
Example #26
0
        private static string GetTableName(Type type, DbContext context)
        {
            MetadataWorkspace metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace;

            // Get the part of the model that contains info about the actual CLR types
            ObjectItemCollection objectItemCollection = (ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace);

            // Get the entity type from the model that maps to the CLR type
            EntityType entityType = metadata
                                    .GetItems <EntityType>(DataSpace.OSpace)
                                    .FirstOrDefault(e => objectItemCollection.GetClrType(e) == type);

            if (entityType == null)
            {
                return(null);
            }

            // Get the entity set that uses this entity type
            EntitySet entitySet = metadata
                                  .GetItems <EntityContainer>(DataSpace.CSpace)
                                  .Single()
                                  .EntitySets
                                  .FirstOrDefault(s => s.ElementType.Name == entityType.Name);

            if (entitySet == null)
            {
                return(null);
            }

            // Find the mapping between conceptual and storage model for this entity set
            EntitySetMapping mapping = metadata.GetItems <EntityContainerMapping>(DataSpace.CSSpace)
                                       .Single()
                                       .EntitySetMappings
                                       .Single(s => s.EntitySet == entitySet);

            if (mapping == null)
            {
                return(null);
            }

            // Find the storage entity set (table) that the entity is mapped
            EntitySet table = mapping
                              .EntityTypeMappings.Single()
                              .Fragments.Single()
                              .StoreEntitySet;

            // Return the table name from the storage entity set
            return(string.Format("[{0}].[{1}]", table.Schema, (string)table.MetadataProperties["Table"].Value ?? table.Name));
        }
        private static IEnumerable <ColumnMappingBuilder> GetColumnMappings(
            EntityType entityType, EntitySetMapping entitySetMapping)
        {
            DebugCheck.NotNull(entityType);
            DebugCheck.NotNull(entitySetMapping);

            return(new[] { entityType }
                   .Concat(GetParents(entityType))
                   .SelectMany(
                       et => entitySetMapping
                       .TypeMappings
                       .Where(stm => stm.Types.Contains(et))
                       .SelectMany(stm => stm.MappingFragments)
                       .SelectMany(mf => mf.ColumnMappings)));
        }
        public static EntitySetMapping AddEntitySetMapping(
            this DbDatabaseMapping databaseMapping, EntitySet entitySet)
        {
            DebugCheck.NotNull(databaseMapping);
            DebugCheck.NotNull(entitySet);

            var entitySetMapping = new EntitySetMapping(entitySet, null);

            databaseMapping
            .EntityContainerMappings
            .Single()
            .AddSetMapping(entitySetMapping);

            return(entitySetMapping);
        }
        private static MappingFragment FindStorageMappingFragmentInStorageMapping(EntitySetMapping storageMapping)
        {
            // Find the storage mapping fragment that the entity is mapped to
            var entityTypeMappings = storageMapping.EntityTypeMappings;
            var entityTypeMapping  = entityTypeMappings.First();
            // using First() because Table-per-Hierarchy (TPH) produces multiple copies of the entity type mapping
            var fragments = entityTypeMapping.Fragments;

            if (fragments.Count() != 1)
            {
                throw new EnumGeneratorException(string.Format("{0} Fragments found.", fragments.Count()));
            }
            var fragment = fragments.Single();

            return(fragment);
        }
Example #30
0
        protected static EntityTypeMapping GetEntityTypeMappingInHierarchy(
            DbDatabaseMapping databaseMapping,
            EntityType entityType)
        {
            EntityTypeMapping entityTypeMapping = databaseMapping.GetEntityTypeMapping(entityType);

            if (entityTypeMapping == null)
            {
                EntitySetMapping entitySetMapping = databaseMapping.GetEntitySetMapping(databaseMapping.Model.GetEntitySet(entityType));
                if (entitySetMapping != null)
                {
                    entityTypeMapping = entitySetMapping.EntityTypeMappings.First <EntityTypeMapping>((Func <EntityTypeMapping, bool>)(etm => entityType.DeclaredProperties.All <EdmProperty>((Func <EdmProperty, bool>)(dp => etm.MappingFragments.First <MappingFragment>().ColumnMappings.Select <ColumnMappingBuilder, EdmProperty>((Func <ColumnMappingBuilder, EdmProperty>)(pm => pm.PropertyPath.First <EdmProperty>())).Contains <EdmProperty>(dp)))));
                }
            }
            return(entityTypeMapping);
        }
Example #31
0
        public void Generate(EntityType entityType, DbDatabaseMapping databaseMapping)
        {
            EntitySet         entitySet          = databaseMapping.Model.GetEntitySet(entityType);
            EntitySetMapping  entitySetMapping   = databaseMapping.GetEntitySetMapping(entitySet) ?? databaseMapping.AddEntitySetMapping(entitySet);
            EntityTypeMapping entityTypeMapping1 = entitySetMapping.EntityTypeMappings.FirstOrDefault <EntityTypeMapping>((Func <EntityTypeMapping, bool>)(m => m.EntityTypes.Contains((EntityTypeBase)entitySet.ElementType))) ?? entitySetMapping.EntityTypeMappings.FirstOrDefault <EntityTypeMapping>();
            EntityType        entityType1        = entityTypeMapping1 != null?entityTypeMapping1.MappingFragments.First <MappingFragment>().Table : databaseMapping.Database.AddTable(entityType.GetRootType().Name);

            EntityTypeMapping entityTypeMapping2 = new EntityTypeMapping((EntitySetMapping)null);
            MappingFragment   mappingFragment    = new MappingFragment(databaseMapping.Database.GetEntitySet(entityType1), (TypeMapping)entityTypeMapping2, false);

            entityTypeMapping2.AddType(entityType);
            entityTypeMapping2.AddFragment(mappingFragment);
            entityTypeMapping2.SetClrType(EntityTypeExtensions.GetClrType(entityType));
            entitySetMapping.AddTypeMapping(entityTypeMapping2);
            new PropertyMappingGenerator(this._providerManifest).Generate(entityType, (IEnumerable <EdmProperty>)entityType.Properties, entitySetMapping, mappingFragment, (IList <EdmProperty>) new List <EdmProperty>(), false);
        }
 // <summary>
 // Initialize a translator for the given entity set mapping.
 // </summary>
 // <param name="setMapping"> Entity set mapping. </param>
 // <returns> Translator. </returns>
 internal static ModificationFunctionMappingTranslator CreateEntitySetTranslator(
     EntitySetMapping setMapping)
 {
     return new EntitySetTranslator(setMapping);
 }