/// <summary>
        /// Verification code invoked for entity sets
        /// </summary>
        /// <param name="item">The entity container being generated</param>
        internal void VerifyLanguageCaseSensitiveCompatibilityForEntitySet(System.Data.Metadata.Edm.EntityContainer item)
        {
            if (_isLanguageCaseSensitive)
            {
                return; // no validation necessary
            }

            Debug.Assert(item != null);

            HashSet <string> set = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            foreach (EntitySetBase entitySetBase in item.BaseEntitySets)
            {
                if (MetadataUtil.IsEntitySet(entitySetBase))
                {
                    EntitySet entitySet = (EntitySet)entitySetBase;
                    if (set.Contains(entitySet.Identity))
                    {
                        AddError(ModelBuilderErrorCode.IncompatibleSettingForCaseSensitiveOption,
                                 EdmSchemaErrorSeverity.Error, new InvalidOperationException(Strings.EntitySetExistsWithDifferentCase(entitySet.Identity)),
                                 item.Name);
                    }
                    else
                    {
                        set.Add(entitySet.Identity);
                    }
                }
            }
        }
 protected virtual void Visit(EntityContainer entityContainer)
 {
     foreach (var set in entityContainer.BaseEntitySets)
     {
         Visit(set);
     }
 }
예제 #3
0
        /// <summary>
        /// Returns the entity container in CSpace or SSpace
        /// </summary>
        /// <param name="name"></param>
        /// <param name="ignoreCase"></param>
        /// <param name="entityContainer"></param>
        /// <returns></returns>
        internal override bool TryGetEntityContainer(string name, bool ignoreCase, out EntityContainer entityContainer)
        {
            if (!base.TryGetEntityContainer(name, ignoreCase, out entityContainer))
            {
                return _modelPerspective.TryGetEntityContainer(name, ignoreCase, out entityContainer);
            }

            return true;
        }
 /// <summary>
 /// Returns all mapping fragments for the given entity set's types and their parent types.
 /// </summary>
  internal static IEnumerable<StorageTypeMapping> GetMappingsForEntitySetAndSuperTypes(StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase childEntityType)
  {
      return MetadataHelper.GetTypeAndParentTypesOf(childEntityType, mappingCollection.EdmItemCollection, true /*includeAbstractTypes*/).SelectMany(
          edmType => 
              edmType.EdmEquals(childEntityType) ? 
                GetMappingsForEntitySetAndType(mappingCollection, container, entitySet, (edmType as EntityTypeBase))
              : GetIsTypeOfMappingsForEntitySetAndType(mappingCollection, container, entitySet, (edmType as EntityTypeBase), childEntityType)
          ).ToList();
  }
 /// <summary>
 /// Returns mappings for the given set/type only if the mapping applies also to childEntittyType either via IsTypeOf or explicitly specifying multiple types in mapping fragments.
 /// </summary>
 private static IEnumerable<StorageTypeMapping> GetIsTypeOfMappingsForEntitySetAndType(StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase entityType, EntityTypeBase childEntityType)
 {
     foreach (var mapping in GetMappingsForEntitySetAndType(mappingCollection, container, entitySet, entityType))
     {
         if (mapping.IsOfTypes.Any(parentType => parentType.IsAssignableFrom(childEntityType)) || mapping.Types.Contains(childEntityType))
         {
             yield return mapping;
         }
     }
 }      
            private Dictionary<EntitySetBase, GeneratedView> SerializedGetGeneratedViews(EntityContainer container)
            {
                Debug.Assert(container != null);

                // Note that extentMappingViews will contain both query and update views.
                Dictionary<EntitySetBase, GeneratedView> extentMappingViews;

                // Get the mapping that has the entity container mapped.
                StorageEntityContainerMapping entityContainerMap = MappingMetadataHelper.GetEntityContainerMap(m_storageMappingItemCollection, container);

                // We get here because memoizer didn't find an entry for the container.
                // It might happen that the entry with generated views already exists for the counterpart container, so check it first.
                EntityContainer counterpartContainer = container.DataSpace == DataSpace.CSpace ? 
                    entityContainerMap.StorageEntityContainer : entityContainerMap.EdmEntityContainer;
                if (m_generatedViewsMemoizer.TryGetValue(counterpartContainer, out extentMappingViews))
                {
                    return extentMappingViews;
                }

                extentMappingViews = new Dictionary<EntitySetBase, GeneratedView>(); 
               
                if (!entityContainerMap.HasViews)
                {
                    return extentMappingViews;
                }

                // If we are in generated views mode.
                if (m_generatedViewsMode)
                {
                    if(ObjectItemCollection.ViewGenerationAssemblies!=null && ObjectItemCollection.ViewGenerationAssemblies.Count>0)
                    {
                        SerializedCollectViewsFromObjectCollection(this.m_storageMappingItemCollection.Workspace, extentMappingViews);
                    }
                    else
                    {
                        SerializedCollectViewsFromReferencedAssemblies(this.m_storageMappingItemCollection.Workspace, extentMappingViews);
                    }
                }

                if (extentMappingViews.Count == 0)
                {
                    // We should change the mode to runtime generation of views.
                    this.m_generatedViewsMode = false;
                    this.SerializedGenerateViews(entityContainerMap, extentMappingViews);
                }

                Debug.Assert(extentMappingViews.Count > 0, "view should be generated at this point");

                return extentMappingViews;
            }
예제 #7
0
        /// <summary>
        /// Load all relationships in this entity container
        /// </summary>
        /// <param name="entityContainer"></param>
        internal void LoadRelationships(md.EntityContainer entityContainer)
        {
            // Check to see if I've already loaded information for this entity container
            if (m_entityContainerMap.ContainsKey(entityContainer))
            {
                return;
            }

            // Load all relationships from this entitycontainer
            foreach (md.EntitySetBase e in entityContainer.BaseEntitySets)
            {
                md.RelationshipSet relationshipSet = e as md.RelationshipSet;
                if (relationshipSet == null)
                {
                    continue;
                }

                // Relationship sets can only contain relationships
                md.RelationshipType relationshipType = (md.RelationshipType)relationshipSet.ElementType;
                md.AssociationType  assocType        = relationshipType as md.AssociationType;

                //
                // Handle only binary Association relationships for now
                //
                if (null == assocType || !IsBinary(relationshipType))
                {
                    continue;
                }

                foreach (md.ReferentialConstraint constraint in assocType.ReferentialConstraints)
                {
                    List <ForeignKeyConstraint> fkConstraintList;
                    ForeignKeyConstraint        fkConstraint = new ForeignKeyConstraint(relationshipType, relationshipSet, constraint);
                    if (!m_parentChildRelationships.TryGetValue(fkConstraint.Pair, out fkConstraintList))
                    {
                        fkConstraintList = new List <ForeignKeyConstraint>();
                        m_parentChildRelationships[fkConstraint.Pair] = fkConstraintList;
                    }
                    //
                    // Theoretically, we can have more than one fk constraint between
                    // the 2 tables (though, it is unlikely)
                    //
                    fkConstraintList.Add(fkConstraint);
                }
            }

            // Mark this entity container as already loaded
            m_entityContainerMap[entityContainer] = entityContainer;
        }
        internal static IEnumerable<StorageTypeMapping> GetMappingsForEntitySetAndType(StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase entityType)
        {
            Debug.Assert(entityType != null, "EntityType parameter should not be null.");
            StorageEntityContainerMapping containerMapping = GetEntityContainerMap(mappingCollection, container);
            StorageSetMapping extentMap = containerMapping.GetSetMapping(entitySet.Name);

            //The Set may have no mapping
            if (extentMap != null)
            {
                //for each mapping fragment of Type we are interested in within the given set
                //Check use of IsOfTypes in Code review
                foreach (StorageTypeMapping typeMap in extentMap.TypeMappings.Where(map => map.Types.Union(map.IsOfTypes).Contains(entityType)))
                {
                    yield return typeMap;
                }
            }
        }
        internal static IEnumerable<StorageEntityTypeModificationFunctionMapping> GetModificationFunctionMappingsForEntitySetAndType(StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase entityType)
        {
            StorageEntityContainerMapping containerMapping = GetEntityContainerMap(mappingCollection, container);

            StorageSetMapping extentMap = containerMapping.GetSetMapping(entitySet.Name);
            StorageEntitySetMapping entitySetMapping = extentMap as StorageEntitySetMapping;

            //The Set may have no mapping
            if (entitySetMapping != null)
            {
                if (entitySetMapping != null) //could be association set mapping
                {
                    foreach (var v in entitySetMapping.ModificationFunctionMappings.Where(functionMap => functionMap.EntityType.Equals(entityType)))
                    {
                        yield return v;
                    }
                }
            }

        }
        protected override void Visit(EntityContainer entityContainer)
        {
            int index;
            if (!this.AddObjectToSeenListAndHashBuilder(entityContainer, out index))
            {
                return;
            }

            this.AddObjectStartDumpToHashBuilder(entityContainer, index);

            #region Inner data visit
            
            this.AddObjectContentToHashBuilder(entityContainer.Identity);
            // Name is covered by Identity

            base.Visit(entityContainer);

            #endregion

            this.AddObjectEndDumpToHashBuilder();
        }
예제 #11
0
 /// <summary>
 /// Returns the extent in the target space, for the given entity container.
 /// </summary>
 /// <param name="entityContainer">name of the entity container in target space</param>
 /// <param name="extentName">name of the extent</param>
 /// <param name="ignoreCase">Whether to do case-sensitive member look up or not</param>
 /// <param name="outSet">extent in target space, if a match is found</param>
 /// <returns>returns true, if a match is found otherwise returns false</returns>
 internal bool TryGetExtent(EntityContainer entityContainer, String extentName, bool ignoreCase, out EntitySetBase outSet)
 {
     // There are no entity containers in the OSpace. So there is no mapping involved.
     // Hence the name should be a valid name in the CSpace.
     return entityContainer.BaseEntitySets.TryGetValue(extentName, ignoreCase, out outSet);
 }
예제 #12
0
 /// <summary>
 /// Change the entity container without doing fixup in the entity set collection
 /// </summary>
 internal void ChangeEntityContainerWithoutCollectionFixup(EntityContainer newEntityContainer)
 {
     _entityContainer = newEntityContainer;
 }
        private void MapFunctions(LoadMethodSessionState session, EntityContainer modelEntityContainer)
        {
            if (_storeFunctions == null || _storeFunctions.Length == 0 || _targetEntityFrameworkVersion < EntityFrameworkVersions.Version3)
            {
                return;
            }

            //
            // Create function imports and appropriate complex types for return parameters and add them to the item collection (session.EdmItemCollection).
            // Create and add function mappings.
            //

            var interestingStoreFunctions = _storeFunctions.Where(
                f => f.IsComposableAttribute &&
                     !f.AggregateAttribute &&
                     f.Parameters.All(p => p.Mode == ParameterMode.In));
            foreach (var storeFunction in interestingStoreFunctions)
            {
                RowType tvfReturnType = TypeHelpers.GetTvfReturnType(storeFunction);
                if (tvfReturnType == null)
                {
                    continue;
                }

                // Create function import name.
                string functionImportName = CreateModelName(storeFunction.Name, session.UsedEntityContainerItemNames);
               
                // Create function import parameters.
                UniqueIdentifierService usedParameterNames = new UniqueIdentifierService(false);
                var parameters = storeFunction.Parameters.Select(p => CreateFunctionImportParameter(p, usedParameterNames)).ToArray();
                var failedStoreParameterName = storeFunction.Parameters.Select(p => p.Name).Except(parameters.Select(p => p.Name)).FirstOrDefault();
                if (failedStoreParameterName != null)
                {
                    session.AddError(Strings.UnableToGenerateFunctionImportParameterName(failedStoreParameterName, storeFunction.Identity),
                        ModelBuilderErrorCode.UnableToGenerateFunctionImportParameterName, EdmSchemaErrorSeverity.Warning, null);
                    continue;
                }

                // Create new complex type and register it in the item collection.
                var complexType = CreateModelComplexTypeForTvfResult(session, functionImportName, tvfReturnType);
                complexType.SetReadOnly();
                session.EdmItemCollection.AddInternal(complexType);

                var collectionType = complexType.GetCollectionType();
                collectionType.SetReadOnly();
                var returnTypeUsage = TypeUsage.Create(collectionType);

                // Create function import and register it in the item collection.
                var functionImport = new EdmFunction(functionImportName, _modelEntityContainerName, DataSpace.CSpace, new EdmFunctionPayload()
                {
                    Name = functionImportName,
                    NamespaceName = _namespaceName,
                    ReturnParameters = new FunctionParameter[] {new FunctionParameter(EdmConstants.ReturnType, returnTypeUsage, ParameterMode.ReturnValue)},
                    Parameters = parameters,
                    DataSpace = DataSpace.CSpace,
                    IsComposable = true,
                    IsFunctionImport = true
                });
                functionImport.SetReadOnly();
                modelEntityContainer.AddFunctionImport(functionImport);

                // Add mapping tuple.
                session.MappingLookups.StoreFunctionToFunctionImport.Add(Tuple.Create(storeFunction, functionImport));
            }
        }
        private void Initialize(EntityContainer storeEntityContainer, IEnumerable<EdmFunction> storeFunctions, string namespaceName, string modelEntityContainerName)
        {
            EDesignUtil.CheckArgumentNull(storeEntityContainer, "storeEntityContainer");
            if (!MetadataUtil.IsStoreType(storeEntityContainer))
            {
                throw EDesignUtil.InvalidStoreEntityContainer(storeEntityContainer.Name, "storeEntityContainer");
            }

            if (namespaceName != null)
            {
                EDesignUtil.CheckStringArgument(namespaceName, "namespaceName");
                string adjustedNamespaceName = CreateValildModelNamespaceName(namespaceName);
                if (adjustedNamespaceName != namespaceName)
                {
                    // the user gave us a bad namespace name
                    throw EDesignUtil.InvalidNamespaceNameArgument(namespaceName);
                }
            }
            
            if (modelEntityContainerName != null)
            {
                EDesignUtil.CheckStringArgument(modelEntityContainerName, "modelEntityContainerName");
                string adjustedEntityContainerName = CreateModelName(modelEntityContainerName);
                if (adjustedEntityContainerName != modelEntityContainerName)
                {
                    throw EDesignUtil.InvalidEntityContainerNameArgument(modelEntityContainerName);
                }
                if (modelEntityContainerName == storeEntityContainer.Name)
                {
                    throw EDesignUtil.DuplicateEntityContainerName(modelEntityContainerName, storeEntityContainer.Name);
                }
            }

            _storeEntityContainer = storeEntityContainer;
            _storeFunctions = storeFunctions != null ? storeFunctions.ToArray() : null;
            _namespaceName = namespaceName;
            _modelEntityContainerName = modelEntityContainerName;
            this._pluralizationServiceHandler = new EntityDesignPluralizationHandler(null);

            SetupFields();
        }
 internal static StorageEntityContainerMapping GetEntityContainerMap(StorageMappingItemCollection mappingCollection, EntityContainer entityContainer)
 {
     ReadOnlyCollection<StorageEntityContainerMapping> entityContainerMaps = mappingCollection.GetItems<StorageEntityContainerMapping>();
     StorageEntityContainerMapping entityContainerMap = null;
     foreach (StorageEntityContainerMapping map in entityContainerMaps)
     {
         if ((entityContainer.Equals(map.EdmEntityContainer))
             || (entityContainer.Equals(map.StorageEntityContainer)))
         {
             entityContainerMap = map;
             break;
         }
     }
     if (entityContainerMap == null)
     {
         throw new MappingException(System.Data.Entity.Strings.Mapping_NotFound_EntityContainer(entityContainer.Name));
     }
     return entityContainerMap;
 }
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] //For EdmItemCollection constructor call.  
                                                                            //Since we pass in empty collection for paths, we do not have any resource exposure here.                                                               
        private IList<EdmSchemaError> InternalGenerateMetadata()
        {
            if (_modelEntityContainer != null)
            {
                _modelEntityContainer = null;
                _mappingLookups = null;
                _edmItemCollection = null;
            }

            LoadMethodSessionState session = new LoadMethodSessionState();

            try
            {
                session.EdmItemCollection = new EdmItemCollection();
                if (this.GenerateForeignKeyProperties && this._targetEntityFrameworkVersion < EntityFrameworkVersions.Version2)
                {
                    session.AddError(Strings.UnableToGenerateForeignKeyPropertiesForV1, ModelBuilderErrorCode.UnableToGenerateForeignKeyPropertiesForV1, EdmSchemaErrorSeverity.Error, null);
                    return session.Errors;
                }

                List<AssociationSet> storeAssociationSets = new List<AssociationSet>();
                CollectAllFkProperties(session);

                EntityContainer modelEntityContainer = new EntityContainer(_modelEntityContainerName, DataSpace.CSpace);

                // create the EntityTypes and EntitySets, and save up the AssociationSets for later.
                foreach (EntitySetBase storeSet in _storeEntityContainer.BaseEntitySets)
                {
                    switch (storeSet.BuiltInTypeKind)
                    {
                        case BuiltInTypeKind.AssociationSet:
                            // save these, and create them after the EntityTypes and EntitySets have been created
                            string errorMessage;
                            if (this.GenerateForeignKeyProperties || !EntityStoreSchemaGenerator.IsFkPartiallyContainedInPK(((AssociationSet)storeSet).ElementType, out errorMessage))
                            {
                                storeAssociationSets.Add((AssociationSet)storeSet);
                            }
                            else
                            {
                                session.AddError(errorMessage, ModelBuilderErrorCode.UnsupportedForeinKeyPattern, EdmSchemaErrorSeverity.Error, null);
                            }
                            break;
                        case BuiltInTypeKind.EntitySet:
                            EntitySet set = (EntitySet)storeSet;
                            session.CandidateCollapsedAssociations.Add(set, new OneToOneMappingSerializer.CollapsedEntityAssociationSet(set));
                            break;
                        default:
                            // error
                            throw EDesignUtil.MissingGenerationPatternForType(storeSet.BuiltInTypeKind);
                    }
                }

                foreach (AssociationSet storeAssociationSet in storeAssociationSets)
                {
                    SaveAssociationForCollapsedAssociationCandidate(session, storeAssociationSet);
                }

                Set<AssociationSet> associationSetsFromCollapseCandidateRejects = new Set<AssociationSet>();
                IEnumerable<OneToOneMappingSerializer.CollapsedEntityAssociationSet> invalidCandidates = FindAllInvalidCollapsedAssociationCandidates(session);

                // now that we have gone through all of the association sets, 
                foreach (OneToOneMappingSerializer.CollapsedEntityAssociationSet collapsed in invalidCandidates)
                {
                    session.CandidateCollapsedAssociations.Remove(collapsed.EntitySet);

                    // just create the entity set and save the association set to be added later
                    EntitySet entitySet = CreateModelEntitySet(session, collapsed.EntitySet);
                    modelEntityContainer.AddEntitySetBase(entitySet);
                    associationSetsFromCollapseCandidateRejects.AddRange(collapsed.AssociationSets);                        
                }

                // create all the associations for the invalid collapsed entity association candidates
                foreach (AssociationSet storeAssociationSet in (IEnumerable<AssociationSet>)associationSetsFromCollapseCandidateRejects)
                {
                    if (!IsAssociationPartOfCandidateCollapsedAssociation(session, storeAssociationSet))
                    {
                        AssociationSet set = CreateModelAssociationSet(session, storeAssociationSet);
                        modelEntityContainer.AddEntitySetBase(set);
                    }
                }
                
                // save the set that needs to be created and mapped
                session.MappingLookups.CollapsedEntityAssociationSets.AddRange(session.CandidateCollapsedAssociations.Values);

                // do this in a seperate loop so we are sure all the necessary EntitySets have been created
                foreach (OneToOneMappingSerializer.CollapsedEntityAssociationSet collapsed in session.MappingLookups.CollapsedEntityAssociationSets)
                {
                    AssociationSet set = CreateModelAssociationSet(session, collapsed);
                    modelEntityContainer.AddEntitySetBase(set);
                }
                if (this._targetEntityFrameworkVersion >= EntityFrameworkVersions.Version2)
                {
                    Debug.Assert(EntityFrameworkVersions.Latest == EntityFrameworkVersions.Version3, "Did you add a new framework version");
                    // add LazyLoadingEnabled=true to the EntityContainer
                    MetadataProperty lazyLoadingAttribute =
                        new MetadataProperty(
                            DesignXmlConstants.EdmAnnotationNamespace + ":" + DesignXmlConstants.LazyLoadingEnabled,
                            TypeUsage.CreateStringTypeUsage(
                                PrimitiveType.GetEdmPrimitiveType(
                                    PrimitiveTypeKind.String),
                                    false,
                                    false),
                            true);
                    modelEntityContainer.AddMetadataProperties(new List<MetadataProperty>() { lazyLoadingAttribute });
                    this._hasAnnotationNamespace = true;
                }

                // Map store functions to function imports.
                MapFunctions(session, modelEntityContainer);
                
                if (!EntityStoreSchemaGenerator.HasErrorSeverityErrors(session.Errors))
                {
                    // add them to the collection so they will work if someone wants to use the collection
                    foreach (EntityType type in session.MappingLookups.StoreEntityTypeToModelEntityType.Values)
                    {
                        type.SetReadOnly();
                        session.EdmItemCollection.AddInternal(type);
                    }

                    foreach (AssociationType type in session.MappingLookups.StoreAssociationTypeToModelAssociationType.Values)
                    {
                        type.SetReadOnly();
                        session.EdmItemCollection.AddInternal(type);
                    }

                    foreach (OneToOneMappingSerializer.CollapsedEntityAssociationSet set in session.MappingLookups.CollapsedEntityAssociationSets)
                    {
                        set.ModelAssociationSet.ElementType.SetReadOnly();
                        session.EdmItemCollection.AddInternal(set.ModelAssociationSet.ElementType);
                    }
                    modelEntityContainer.SetReadOnly();
                    session.EdmItemCollection.AddInternal(modelEntityContainer);

                    _modelEntityContainer = modelEntityContainer;
                    _mappingLookups = session.MappingLookups;
                    _edmItemCollection = session.EdmItemCollection;
                }

            }
            catch (Exception e)
            {
                if (MetadataUtil.IsCatchableExceptionType(e))
                {
                    // an exception in the code is definitely an error
                    string message = EDesignUtil.GetMessagesFromEntireExceptionChain(e);
                    session.AddError(message,
                    ModelBuilderErrorCode.UnknownError,
                    EdmSchemaErrorSeverity.Error,
                    e);
                }
                else
                {
                    throw;
                }

            }
            return session.Errors;
        }
            /// <summary>
            /// Generates a single query view for a given Extent and type. It is used to generate OfType and OfTypeOnly views.
            /// </summary>
            /// <param name="includeSubtypes">Whether the view should include extents that are subtypes of the given entity</param>
            private bool TryGenerateQueryViewOfType(EntityContainer entityContainer, EntitySetBase entity, EntityTypeBase type, bool includeSubtypes, out GeneratedView generatedView)
            {
                Debug.Assert(entityContainer != null);
                Debug.Assert(entity != null);
                Debug.Assert(type != null);

                if (type.Abstract)
                {
                    generatedView = null;
                    return false;
                }

                //Get the mapping that has the entity container mapped.
                StorageEntityContainerMapping entityContainerMap = MappingMetadataHelper.GetEntityContainerMap(m_storageMappingItemCollection, entityContainer);
                Debug.Assert(!entityContainerMap.IsEmpty, "There are no entity set maps");

                bool success;
                ViewGenResults viewGenResults = ViewgenGatekeeper.GenerateTypeSpecificQueryView(entityContainerMap, m_config, entity, type, includeSubtypes, out success);
                if (!success)
                {
                    generatedView = null;
                    return false; //could not generate view
                }

                KeyToListMap<EntitySetBase, GeneratedView> extentMappingViews = viewGenResults.Views;

                if (viewGenResults.HasErrors)
                {
                    throw new MappingException(Helper.CombineErrorMessage(viewGenResults.Errors));
                }

                Debug.Assert(extentMappingViews.AllValues.Count() == 1, "Viewgen should have produced only one view");
                generatedView = extentMappingViews.AllValues.First();

                return true;
            }
 /// <summary>
 /// Returns the extent in the target space, for the given entity container.
 /// </summary>
 /// <param name="entityContainer">name of the entity container in target space</param>
 /// <param name="extentName">name of the extent</param>
 /// <param name="ignoreCase">Whether to do case-sensitive member look up or not</param>
 /// <param name="outSet">extent in target space, if a match is found</param>
 /// <returns>returns true, if a match is found otherwise returns false</returns>
 internal bool TryGetExtent(EntityContainer entityContainer, String extentName, bool ignoreCase, out EntitySetBase outSet)
 {
     // There are no entity containers in the OSpace. So there is no mapping involved.
     // Hence the name should be a valid name in the CSpace.
     return(entityContainer.BaseEntitySets.TryGetValue(extentName, ignoreCase, out outSet));
 }
        /// <summary>
        /// Gets MetadataItem object for URI relative path under the specified EntityContainer instance 
        /// </summary>
        /// <param name="container">The EntityContainer instance</param>
        /// <param name="pathSegment">The URI relative path</param>
        /// <param name="uriType">Output parameter of UriType value</param>
        /// <returns>The MetadataItem instance if one is found; null otherwise</returns>
        private static MetadataItem GetTargetType(EntityContainer container, IEnumerable<string> pathSegment, ref UriType uriType)
        {
            ODataUriItem curr = new ODataUriItem(container, UriType.URI_Container);
            foreach (var segment in pathSegment)
            {
                // to normalize first segment
                string segmentKey;
                string segmentCore = ResourcePathHelper.ParseSegment(segment, out segmentKey);
                ODataUriItem subItem = curr.GetItem(segmentCore);
                if (subItem == null)
                {
                    uriType = UriType.URIUNKNOWN;
                    return null;
                }

                if (subItem.uriType == UriType.URI1 && !string.IsNullOrEmpty(segmentKey))
                {
                    subItem = new ODataUriItem(((EntitySet)subItem.Item).ElementType, UriType.URI2);
                }

                curr = subItem;
            }

            uriType = curr.uriType;
            return curr.Item;
        }
        // Caller can specify that the results should not be sorted if they may add something to the list and sort themselves
        internal List<EntityDataSourceEntitySetNameItem> GetEntitySets(EntityContainer entityContainer, bool sortResults)
        {
            List<EntityDataSourceEntitySetNameItem> entitySetNameItems = new List<EntityDataSourceEntitySetNameItem>();
            if (entityContainer != null)
            {
                foreach (EntitySetBase entitySetBase in entityContainer.BaseEntitySets)
                {
                    // BaseEntitySets returns RelationshipSets too, but we only want EntitySets
                    if (entitySetBase.BuiltInTypeKind == BuiltInTypeKind.EntitySet)
                    {
                        entitySetNameItems.Add(new EntityDataSourceEntitySetNameItem(entitySetBase as EntitySet));
                    }
                }

                if (sortResults)
                {
                    entitySetNameItems.Sort();
                }
            }
            return entitySetNameItems;
        }
예제 #21
0
 /// <summary>
 /// Get an entity container based upon the strong name of the container
 /// If no entity container is found, returns null, else returns the first one/// </summary>
 /// <param name="name">name of the entity container</param>
 /// <param name="entityContainer"></param>
 /// <exception cref="System.ArgumentNullException">if name argument is null</exception>
 public bool TryGetEntityContainer(string name, out EntityContainer entityContainer)
 {
     EntityUtil.GenericCheckArgumentNull(name, "name");
     return(this.TryGetEntityContainer(name, false /*ignoreCase*/, out entityContainer));
 }
예제 #22
0
 internal void SetDefaultContainer(string defaultContainerName)
 {
     EntityContainer container = null;
     if (!String.IsNullOrEmpty(defaultContainerName))
     {
         if (!MetadataWorkspace.TryGetEntityContainer(defaultContainerName, DataSpace.CSpace, out container))
         {
             throw new ArgumentException(
                 Strings.ObjectContext_InvalidDefaultContainerName(defaultContainerName), "defaultContainerName");
         }
     }
     _defaultContainer = container;
 }
 internal EntityContainerExpression(EntityContainer entityContainer)
     : base(ExpressionResolutionClass.EntityContainer)
 {
     EntityContainer = entityContainer;
 }
예제 #24
0
 /// <summary>
 /// The constructor for constructing the collection with the given items
 /// </summary>
 /// <param name="entityContainer">The entity container that has this entity set collection</param>
 /// <param name="items">The items to populate the collection</param>
 /// <exception cref="System.ArgumentNullException">Thrown if the argument entityContainer is null</exception>
 internal EntitySetBaseCollection(EntityContainer entityContainer, IEnumerable <EntitySetBase> items)
     : base(items)
 {
     EntityUtil.GenericCheckArgumentNull(entityContainer, "entityContainer");
     _entityContainer = entityContainer;
 }
예제 #25
0
 /// <summary>
 /// Returns mappings for the given set/type only if the mapping applies also to childEntittyType either via IsTypeOf or explicitly specifying multiple types in mapping fragments.
 /// </summary>
 private static IEnumerable <StorageTypeMapping> GetIsTypeOfMappingsForEntitySetAndType(StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase entityType, EntityTypeBase childEntityType)
 {
     foreach (var mapping in GetMappingsForEntitySetAndType(mappingCollection, container, entitySet, entityType))
     {
         if (mapping.IsOfTypes.Any(parentType => parentType.IsAssignableFrom(childEntityType)) || mapping.Types.Contains(childEntityType))
         {
             yield return(mapping);
         }
     }
 }
예제 #26
0
        internal static StorageEntityContainerMapping GetEntityContainerMap(StorageMappingItemCollection mappingCollection, EntityContainer entityContainer)
        {
            ReadOnlyCollection <StorageEntityContainerMapping> entityContainerMaps = mappingCollection.GetItems <StorageEntityContainerMapping>();
            StorageEntityContainerMapping entityContainerMap = null;

            foreach (StorageEntityContainerMapping map in entityContainerMaps)
            {
                if ((entityContainer.Equals(map.EdmEntityContainer)) ||
                    (entityContainer.Equals(map.StorageEntityContainer)))
                {
                    entityContainerMap = map;
                    break;
                }
            }
            if (entityContainerMap == null)
            {
                throw new MappingException(System.Data.Entity.Strings.Mapping_NotFound_EntityContainer(entityContainer.Name));
            }
            return(entityContainerMap);
        }
예제 #27
0
 /// <summary>
 /// Returns all mapping fragments for the given entity set's types and their parent types.
 /// </summary>
 internal static IEnumerable <StorageTypeMapping> GetMappingsForEntitySetAndSuperTypes(StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase childEntityType)
 {
     return(MetadataHelper.GetTypeAndParentTypesOf(childEntityType, mappingCollection.EdmItemCollection, true /*includeAbstractTypes*/).SelectMany(
                edmType =>
                edmType.EdmEquals(childEntityType) ?
                GetMappingsForEntitySetAndType(mappingCollection, container, entitySet, (edmType as EntityTypeBase))
             : GetIsTypeOfMappingsForEntitySetAndType(mappingCollection, container, entitySet, (edmType as EntityTypeBase), childEntityType)
                ).ToList());
 }
 /// <summary>
 /// Get an entity container based upon the strong name of the container
 /// If no entity container is found, returns null, else returns the first one/// </summary>
 /// <param name="name">name of the entity container</param>
 /// <param name="ignoreCase">true for case-insensitive lookup</param>
 /// <param name="entityContainer">returns the entity container if a match is found</param>
 /// <returns>returns true if a match is found, otherwise false</returns>
 internal virtual bool TryGetEntityContainer(string name, bool ignoreCase, out EntityContainer entityContainer)
 {
     return(MetadataWorkspace.TryGetEntityContainer(name, ignoreCase, TargetDataspace, out entityContainer));
 }
예제 #29
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="generator"></param>
 /// <param name="entityContainer"></param>
 public EntityContainerEmitter(ClientApiGenerator generator, EntityContainer entityContainer)
     : base(generator, entityContainer)
 {
 }
 /// <summary>
 /// Change the entity container without doing fixup in the entity set collection
 /// </summary>
 internal void ChangeEntityContainerWithoutCollectionFixup(EntityContainer newEntityContainer)
 {
     _entityContainer = newEntityContainer;
 }
예제 #31
0
        // This collection allows changes to be intercepted before and after they are passed to MetadataCollection.  The interception
        // is required to update the EntitySet's back-reference to the EntityContainer.

        #region Constructors
        /// <summary>
        /// Default constructor for constructing an empty collection
        /// </summary>
        /// <param name="entityContainer">The entity container that has this entity set collection</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the argument entityContainer is null</exception>
        internal EntitySetBaseCollection(EntityContainer entityContainer)
            : this(entityContainer, null)
        {
        }
 /// <summary>
 /// Constructs an EntityModelGenerator
 /// </summary>
 /// <param name="storeEntityContainer"></param>
 public EntityModelSchemaGenerator(EntityContainer storeEntityContainer)
 {
     Initialize(storeEntityContainer, null, null, null);
 }
예제 #33
0
 internal void SetDefaultContainer(string defaultContainerName)
 {
     EntityContainer container = null;
     if (!String.IsNullOrEmpty(defaultContainerName))
     {
         if (!MetadataWorkspace.TryGetEntityContainer(defaultContainerName, DataSpace.CSpace, out container))
         {
             throw EntityUtil.InvalidDefaultContainerName("defaultContainerName", defaultContainerName);
         }
     }
     _defaultContainer = container;
 }
 /// <summary>
 /// Constructs an EntityModelGenerator
 /// </summary>
 /// <param name="storeEntityContainer">The Store EntityContainer to create the Model Metadata from.</param>
 /// <param name="namespaceName">The name to give the namespace. If null, the name of the storeEntityContainer will be used.</param>
 /// <param name="modelEntityContainerName">The name to give the Model EntityContainer. If null, a modified version of the namespace of the of a type referenced in storeEntityContainer will be used.</param>
 public EntityModelSchemaGenerator(EntityContainer storeEntityContainer, string namespaceName, string modelEntityContainerName)
 {
     EDesignUtil.CheckArgumentNull(namespaceName, "namespaceName");
     EDesignUtil.CheckArgumentNull(modelEntityContainerName, "modelEntityContainerName");
     Initialize(storeEntityContainer, null, namespaceName, modelEntityContainerName);
 }
예제 #35
0
        internal static IEnumerable <StorageTypeMapping> GetMappingsForEntitySetAndType(StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase entityType)
        {
            Debug.Assert(entityType != null, "EntityType parameter should not be null.");
            StorageEntityContainerMapping containerMapping = GetEntityContainerMap(mappingCollection, container);
            StorageSetMapping             extentMap        = containerMapping.GetSetMapping(entitySet.Name);

            //The Set may have no mapping
            if (extentMap != null)
            {
                //for each mapping fragment of Type we are interested in within the given set
                //Check use of IsOfTypes in Code review
                foreach (StorageTypeMapping typeMap in extentMap.TypeMappings.Where(map => map.Types.Union(map.IsOfTypes).Contains(entityType)))
                {
                    yield return(typeMap);
                }
            }
        }
예제 #36
0
 /// <summary>
 /// Get an entity container based upon the strong name of the container
 /// If no entity container is found, returns null, else returns the first one/// </summary>
 /// <param name="name">name of the entity container</param>
 /// <param name="ignoreCase">true for case-insensitive lookup</param>
 /// <param name="entityContainer">returns the entity container if a match is found</param>
 /// <returns>returns true if a match is found, otherwise false</returns>
 internal virtual bool TryGetEntityContainer(string name, bool ignoreCase, out EntityContainer entityContainer)
 {
     return MetadataWorkspace.TryGetEntityContainer(name, ignoreCase, TargetDataspace, out entityContainer);
 }
 internal OneToOneMappingSerializer(MappingLookups lookups,
     EntityContainer storeContainer,
     EntityContainer modelContainer,
     Version schemaVersion)
 {
     EDesignUtil.CheckArgumentNull(lookups, "lookups");
     EDesignUtil.CheckArgumentNull(storeContainer, "storeContainer");
     EDesignUtil.CheckArgumentNull(modelContainer, "modelContainer");
     _lookups = lookups;
     _storeContainer = storeContainer;
     _modelContainer = modelContainer;
     _xmlNamespace = EntityFrameworkVersions.GetSchemaNamespace(schemaVersion, DataSpace.CSSpace);
 }
예제 #38
0
 /// <summary>
 /// Returns the function import in the target space, for the given entity container.
 /// </summary>
 internal bool TryGetFunctionImport(EntityContainer entityContainer, String functionImportName, bool ignoreCase, out EdmFunction functionImport)
 {
     // There are no entity containers in the OSpace. So there is no mapping involved.
     // Hence the name should be a valid name in the CSpace.
     functionImport = null;
     if (ignoreCase)
     {
         functionImport = entityContainer.FunctionImports.Where(fi => String.Equals(fi.Name, functionImportName, StringComparison.OrdinalIgnoreCase)).SingleOrDefault();
     }
     else
     {
         functionImport = entityContainer.FunctionImports.Where(fi => fi.Name == functionImportName).SingleOrDefault();
     }
     return functionImport != null;
 }
        /// <summary>
        /// Creates 'transient' metadataworkspace based on store schema (EntityContainer) and trivial C-S mapping
        /// </summary>
        /// <param name="entityContainer"></param>
        /// <param name="session"></param>
        /// <returns></returns>
        private MetadataWorkspace CreateMetadataWorkspace(EntityContainer entityContainer, LoadMethodSessionState session)
        {
            MetadataWorkspace metadataWorkspace = new MetadataWorkspace();
            
            EntityModelSchemaGenerator modelGen = new EntityModelSchemaGenerator(entityContainer);
            modelGen.GenerateForeignKeyProperties = this.GenerateForeignKeyProperties;

            IEnumerable<EdmSchemaError> errors = modelGen.GenerateMetadata();

            if (EntityStoreSchemaGenerator.HasErrorSeverityErrors(errors))
            {
                // this is a 'transient' metadataworkspace 
                // no errors from this metadataworkspace should be shown to the user
                return null;
            }

            // register edmitemcollection
            metadataWorkspace.RegisterItemCollection(modelGen.EdmItemCollection);
            
            // register StoreItemCollection
            metadataWorkspace.RegisterItemCollection(session.ItemCollection);

            // register mapping
            using (MemoryStream memStream = new MemoryStream())
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(memStream))
                {
                    modelGen.WriteStorageMapping(xmlWriter);
                    xmlWriter.Close();
                }
                
                memStream.Seek(0, SeekOrigin.Begin);

                using (XmlReader xmlReader = XmlReader.Create(memStream))
                {
                    List<XmlReader> xmlReaders = new List<XmlReader>();
                    xmlReaders.Add(xmlReader);
                    metadataWorkspace.RegisterItemCollection(new StorageMappingItemCollection(modelGen.EdmItemCollection, 
                                                                                              session.ItemCollection, 
                                                                                              xmlReaders));
                }
            }

            return metadataWorkspace;
        }
        // effects: Given a store-side container, returns all the foreign key
        // constraints specified for different tables
        internal static List<ForeignConstraint> GetForeignConstraints(EntityContainer container)
        {
            var foreignKeyConstraints = new List<ForeignConstraint>();

            // Go through all the extents and get the associations
            foreach (var extent in container.BaseEntitySets)
            {
                var relationSet = extent as AssociationSet;

                if (relationSet == null)
                {
                    continue;
                }
                // Keep track of the end to EntitySet mapping
                var endToExtents = new Dictionary<string, EntitySet>();

                foreach (var end in relationSet.AssociationSetEnds)
                {
                    endToExtents.Add(end.Name, end.EntitySet);
                }

                var relationType = relationSet.ElementType;
                // Go through each referential constraint, determine the name
                // of the tables that the constraint refers to and then
                // create the foreign key constraint between the tables
                // Wow! We go to great lengths to make it cumbersome for a
                // programmer to deal with foreign keys
                foreach (var constraint in relationType.ReferentialConstraints)
                {
                    // Note: We are correlating the constraint's roles with
                    // the ends above using the role names, i.e.,
                    // FromRole.Name and ToRole.Name here and end.Role above
                    var parentExtent = endToExtents[constraint.FromRole.Name];
                    var childExtent = endToExtents[constraint.ToRole.Name];
                    var foreignKeyConstraint = new ForeignConstraint(
                        relationSet, parentExtent, childExtent,
                        constraint.FromProperties, constraint.ToProperties);
                    foreignKeyConstraints.Add(foreignKeyConstraint);
                }
            }
            return foreignKeyConstraints;
        }
        /// <summary>
        /// Populates DefiningQuery attribute of RO view entities
        /// </summary>
        /// <param name="viewEntitySets"></param>
        /// <param name="entityContainer"></param>
        /// <param name="session"></param>
        private void FixupKeylessEntitySets(EntityContainer entityContainer, LoadMethodSessionState session)
        {
            // if there are views to process
            if (session.ReadOnlyEntities.Count > 0)
            {
                //
                // create 'bogus' metadataworkspace
                //
                MetadataWorkspace metadataWorkspace = CreateMetadataWorkspace(entityContainer, session);

                if (null == metadataWorkspace)
                {
                    // failed to create bogus metadataworkspace
                    return;
                }

                //
                // For all tables/views that we could infer valid keys, update DefiningQuery with 
                // provider specific ReadOnly view SQL
                //
                foreach (EntityType entityType in session.ReadOnlyEntities)
                {
                    EntitySet entitySet = session.EntityTypeToSet[entityType];
                    DbObjectKey key = session.GetKey(entityType);
                    
                    // add properties that make it possible for the designer to track back these 
                    // types to their source db objects
                    List<MetadataProperty> properties = new List<MetadataProperty>();
                    if (key.Schema != null)
                    {
                        properties.Add(System.Data.EntityModel.SchemaObjectModel.SchemaElement.CreateMetadataPropertyFromOtherNamespaceXmlArtifact(DesignXmlConstants.EntityStoreSchemaGeneratorNamespace, DesignXmlConstants.EntityStoreSchemaGeneratorSchemaAttributeName, key.Schema));
                    }
                    properties.Add(System.Data.EntityModel.SchemaObjectModel.SchemaElement.CreateMetadataPropertyFromOtherNamespaceXmlArtifact(DesignXmlConstants.EntityStoreSchemaGeneratorNamespace, DesignXmlConstants.EntityStoreSchemaGeneratorNameAttributeName, key.TableName));
                    entitySet.AddMetadataProperties(properties);

                    FixupViewEntitySetDefiningQuery(entitySet, metadataWorkspace);
                }
            }
        }
예제 #42
0
        /// <summary>
        /// Gets sub item of the specified EntityContainer instance by the name 
        /// </summary>
        /// <param name="container">The EntityContainer instance</param>
        /// <param name="name">The name of sub item</param>
        /// <returns>sub item object if one is found; null otherwise</returns>
        private static ODataUriItem GetItem(EntityContainer container, string name)
        {
            ODataUriItem result = null;

            EntitySet entitySet;
            bool isEntitySet = container.TryGetEntitySetByName(name, false, out entitySet);
            if (isEntitySet)
            {
                return new ODataUriItem(entitySet, UriType.URI1);
            }
            else
            {
                var fs = container.FunctionImports.Where(x => x.Name.Equals(name, StringComparison.Ordinal));
                if (fs.Any())
                {
                    EdmFunction func = fs.First();
                    var retVal = func.ReturnParameter;
                    var retType = retVal.TypeUsage.EdmType;
                    UriType retUriType = GetUriTypeOfFuncReturn(retType);
                    if (retUriType == UriType.URI11 || retUriType == UriType.URI13 || retUriType == UriType.URI_CollEt)
                    {
                        result = new ODataUriItem(((CollectionType)retType).TypeUsage.EdmType, retUriType);
                    }
                    else
                    {
                        result = new ODataUriItem(retType, retUriType);
                    }
                }
            }

            return result;
        }
예제 #43
0
        internal static IEnumerable <StorageEntityTypeModificationFunctionMapping> GetModificationFunctionMappingsForEntitySetAndType(StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase entityType)
        {
            StorageEntityContainerMapping containerMapping = GetEntityContainerMap(mappingCollection, container);

            StorageSetMapping       extentMap        = containerMapping.GetSetMapping(entitySet.Name);
            StorageEntitySetMapping entitySetMapping = extentMap as StorageEntitySetMapping;

            //The Set may have no mapping
            if (entitySetMapping != null)
            {
                if (entitySetMapping != null) //could be association set mapping
                {
                    foreach (var v in entitySetMapping.ModificationFunctionMappings.Where(functionMap => functionMap.EntityType.Equals(entityType)))
                    {
                        yield return(v);
                    }
                }
            }
        }