Exemplo n.º 1
0
        /// <summary>
        /// Initializes a new command tree with a given metadata workspace.
        /// </summary>
        /// <param name="metadata">The metadata workspace against which the command tree should operate.</param>
        /// <param name="dataSpace">The logical 'space' that metadata in the expressions used in this command tree must belong to.</param>
        internal DbCommandTree(MetadataWorkspace metadata, DataSpace dataSpace)
        {
            // Ensure the metadata workspace is non-null
            //Contract.Requires(metadata != null);

            // Ensure that the data space value is valid
            if (!IsValidDataSpace(dataSpace))
            {
                throw new ArgumentException(Strings.Cqt_CommandTree_InvalidDataSpace, "dataSpace");
            }

            //
            // Create the tree's metadata workspace and initalize commonly used types.
            //
            var effectiveMetadata = new MetadataWorkspace();

            //While EdmItemCollection and StorageitemCollections are required
            //ObjectItemCollection may or may not be registered on the workspace yet.
            //So register the ObjectItemCollection if it exists.
            ItemCollection objectItemCollection;
            if (metadata.TryGetItemCollection(DataSpace.OSpace, out objectItemCollection))
            {
                effectiveMetadata.RegisterItemCollection(objectItemCollection);
            }
            effectiveMetadata.RegisterItemCollection(metadata.GetItemCollection(DataSpace.CSpace));
            effectiveMetadata.RegisterItemCollection(metadata.GetItemCollection(DataSpace.CSSpace));
            effectiveMetadata.RegisterItemCollection(metadata.GetItemCollection(DataSpace.SSpace));

            _metadata = effectiveMetadata;
            _dataSpace = dataSpace;
        }
Exemplo n.º 2
0
        /// <summary>
        /// Initializes a new command tree with a given metadata workspace.
        /// </summary>
        /// <param name="metadata">The metadata workspace against which the command tree should operate.</param>
        /// <param name="dataSpace">The logical 'space' that metadata in the expressions used in this command tree must belong to.</param>
        internal DbCommandTree(MetadataWorkspace metadata, DataSpace dataSpace)
        {
            // Ensure the metadata workspace is non-null
            EntityUtil.CheckArgumentNull(metadata, "metadata");

            // Ensure that the data space value is valid
            if (!DbCommandTree.IsValidDataSpace(dataSpace))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_CommandTree_InvalidDataSpace, "dataSpace");
            }

            //
            // Create the tree's metadata workspace and initalize commonly used types.
            //
            MetadataWorkspace effectiveMetadata = new MetadataWorkspace();

            //While EdmItemCollection and StorageitemCollections are required
            //ObjectItemCollection may or may not be registered on the workspace yet.
            //So register the ObjectItemCollection if it exists.
            ItemCollection objectItemCollection;

            if (metadata.TryGetItemCollection(DataSpace.OSpace, out objectItemCollection))
            {
                effectiveMetadata.RegisterItemCollection(objectItemCollection);
            }
            effectiveMetadata.RegisterItemCollection(metadata.GetItemCollection(DataSpace.CSpace));
            effectiveMetadata.RegisterItemCollection(metadata.GetItemCollection(DataSpace.CSSpace));
            effectiveMetadata.RegisterItemCollection(metadata.GetItemCollection(DataSpace.SSpace));

            this._metadata  = effectiveMetadata;
            this._dataSpace = dataSpace;
        }
            public void GetItemCollection_on_both_CS_and_S_space_using_item_collections_with_inconsistent_versions_throws_MetadataException()
            {
                var edmItemCollection            = new EdmItemCollection(new[] { XDocument.Parse(_csdlV3).CreateReader() });
                var storeItemCollection          = new StoreItemCollection(new[] { XDocument.Parse(_ssdlV3).CreateReader() });
                var storageMappingItemCollection = LoadMsl(edmItemCollection, storeItemCollection);

                // edmItemCollection and storeItemCollection must have the same version to generate storageMappingItemCollection
                // here we override the storeItemCollection so that it's version will be different for the MetadataWorkspace
                storeItemCollection =
                    new StoreItemCollection(
                        new[]
                {
                    XDocument.Parse(string.Format(CultureInfo.InvariantCulture, SsdlTemplate, XmlConstants.TargetNamespace_2))
                    .CreateReader()
                });

                var workspace = new MetadataWorkspace(
                    () => null,
                    () => storeItemCollection,
                    () => storageMappingItemCollection);

                workspace.GetItemCollection(DataSpace.SSpace); // this sets up the MetadataWorkspace's expected schema version as the ssdl version i.e. 2.0
                Assert.Equal(
                    Resources.Strings.DifferentSchemaVersionInCollection("StorageMappingItemCollection", 3.0, 2.0),
                    Assert.Throws <MetadataException>(() => workspace.GetItemCollection(DataSpace.CSSpace)).Message);
            }
Exemplo n.º 4
0
        /// <summary>
        /// Initializes a new command tree with a given metadata workspace.
        /// </summary>
        /// <param name="metadata">The metadata workspace against which the command tree should operate.</param>
        /// <param name="dataSpace">The logical 'space' that metadata in the expressions used in this command tree must belong to.</param>
        internal DbCommandTree(MetadataWorkspace metadata, DataSpace dataSpace)
        {
            // Ensure the metadata workspace is non-null
            EntityUtil.CheckArgumentNull(metadata, "metadata");

            // Ensure that the data space value is valid
            if (!DbCommandTree.IsValidDataSpace(dataSpace))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_CommandTree_InvalidDataSpace, "dataSpace");
            }

            //
            // Create the tree's metadata workspace and initalize commonly used types.
            //
            MetadataWorkspace effectiveMetadata = new MetadataWorkspace();
                
            //While EdmItemCollection and StorageitemCollections are required
            //ObjectItemCollection may or may not be registered on the workspace yet.
            //So register the ObjectItemCollection if it exists.
            ItemCollection objectItemCollection;
            if (metadata.TryGetItemCollection(DataSpace.OSpace, out objectItemCollection))
            {
                effectiveMetadata.RegisterItemCollection(objectItemCollection);
            }                
            effectiveMetadata.RegisterItemCollection(metadata.GetItemCollection(DataSpace.CSpace));
            effectiveMetadata.RegisterItemCollection(metadata.GetItemCollection(DataSpace.CSSpace));
            effectiveMetadata.RegisterItemCollection(metadata.GetItemCollection(DataSpace.SSpace));

            this._metadata = effectiveMetadata;
            this._dataSpace = dataSpace;
        }
Exemplo n.º 5
0
        /// <summary>
        /// Generates metadata for given item collection.
        /// Fetches CLR models from given assembly.
        /// </summary>
        /// <param name="metadataWorkspace">The metadata workspace.</param>
        /// <param name="modelAssembly">The model assembly.</param>
        /// <param name="connectionString">The connection string.</param>
        /// <returns></returns>
        public static Metadata Generate(MetadataWorkspace metadataWorkspace, Assembly modelAssembly, string connectionString) {
            metadataWorkspace.RegisterItemCollection(new ObjectItemCollection());
            metadataWorkspace.LoadFromAssembly(modelAssembly);

            var itemCollection = metadataWorkspace.GetItemCollection(DataSpace.CSpace);
            var objectItemCollection = (ObjectItemCollection)metadataWorkspace.GetItemCollection(DataSpace.OSpace);

            return Generate(metadataWorkspace, itemCollection, objectItemCollection, modelAssembly, connectionString);
        }
        // <summary>
        // Updates the cache of types to entity sets either for the first time or after potentially
        // doing some o-space loading.
        // </summary>
        private void UpdateEntitySetMappings()
        {
            var objectItemCollection = (ObjectItemCollection)_workspace.GetItemCollection(DataSpace.OSpace);
            var ospaceTypes          = _workspace.GetItems <EntityType>(DataSpace.OSpace);
            var inverseHierarchy     = new Stack <EntityType>();

            foreach (var ospaceType in ospaceTypes)
            {
                inverseHierarchy.Clear();
                var cspaceType = (EntityType)_workspace.GetEdmSpaceType(ospaceType);
                do
                {
                    inverseHierarchy.Push(cspaceType);
                    cspaceType = (EntityType)cspaceType.BaseType;
                }while (cspaceType != null);

                EntitySet entitySet = null;
                while (entitySet == null &&
                       inverseHierarchy.Count > 0)
                {
                    cspaceType = inverseHierarchy.Pop();
                    foreach (var container in _workspace.GetItems <EntityContainer>(DataSpace.CSpace))
                    {
                        var entitySets      = container.BaseEntitySets.Where(s => s.ElementType == cspaceType).ToList();
                        var entitySetsCount = entitySets.Count;
                        if (entitySetsCount > 1 ||
                            entitySetsCount == 1 && entitySet != null)
                        {
                            throw Error.DbContext_MESTNotSupported();
                        }
                        if (entitySetsCount == 1)
                        {
                            entitySet = (EntitySet)entitySets[0];
                        }
                    }
                }

                // Entity set may be null if the o-space type is a base type that is in the model but is
                // not part of any set.  For most practical purposes, this type is not in the model since
                // there is no way to query etc. for objects of this type.
                if (entitySet != null)
                {
                    var ospaceBaseType = (EntityType)_workspace.GetObjectSpaceType(cspaceType);
                    var clrType        = objectItemCollection.GetClrType(ospaceType);
                    var clrBaseType    = objectItemCollection.GetClrType(ospaceBaseType);
                    _entitySetMappingsCache[clrType] = new EntitySetTypePair(entitySet, clrBaseType);
                }
            }
        }
Exemplo n.º 7
0
        internal static Type GetClrTypeFromCSpaceType(this MetadataWorkspace workspace, EdmType conceptualType)
        {
            var itemCollection = (ObjectItemCollection)workspace.GetItemCollection(DataSpace.OSpace);

            if (conceptualType is StructuralType)
            {
                var objectSpaceType = workspace.GetObjectSpaceType((StructuralType)conceptualType);
                return(itemCollection.GetClrType(objectSpaceType));
            }
            else if (conceptualType is EnumType)
            {
                var objectSpaceType = workspace.GetObjectSpaceType((EnumType)conceptualType);
                return(itemCollection.GetClrType(objectSpaceType));
            }
            else if (conceptualType is PrimitiveType)
            {
                return(((PrimitiveType)conceptualType).ClrEquivalentType);
            }
            else if (conceptualType is CollectionType)
            {
                return(workspace.GetClrTypeFromCSpaceType(((CollectionType)conceptualType).TypeUsage.EdmType));
            }
            else if (conceptualType is RefType)
            {
                return(workspace.GetClrTypeFromCSpaceType(((RefType)conceptualType).ElementType));
            }
            else if (conceptualType is EdmFunction)
            {
                return(workspace.GetClrTypeFromCSpaceType(((EdmFunction)conceptualType).ReturnParameter.TypeUsage.EdmType));
            }

            return(null);
        }
            /// <summary>
            /// this method do the following check on the generated views in the EntityViewContainer,
            /// then add those views all at once to the dictionary
            /// 1. there should be one storeageEntityContainerMapping that has the same h
            ///     C side and S side names as the EnittyViewcontainer
            /// 2. Generate the hash for the storageEntityContainerMapping in the MM closure,
            ///     and this hash should be the same in EntityViewContainer
            /// 3. Generate the hash for all of the view text in the EntityViewContainer and
            ///     this hash should be the same as the stored on in the EntityViewContainer
            /// </summary>
            /// <param name="entityViewContainer"></param>
            private void SerializedAddGeneratedViewsInEntityViewContainer(MetadataWorkspace workspace, EntityViewContainer entityViewContainer, Dictionary <EntitySetBase, GeneratedView> extentMappingViews)
            {
                StorageEntityContainerMapping storageEntityContainerMapping;

                // first check
                if (!this.TryGetCorrespondingStorageEntityContainerMapping(entityViewContainer,
                                                                           workspace.GetItemCollection(DataSpace.CSSpace).GetItems <StorageEntityContainerMapping>(), out storageEntityContainerMapping))
                {
                    return;
                }

                // second check
                if (!this.SerializedVerifyHashOverMmClosure(storageEntityContainerMapping, entityViewContainer))
                {
                    throw new MappingException(Strings.ViewGen_HashOnMappingClosure_Not_Matching(entityViewContainer.EdmEntityContainerName));
                }

                // third check, prior to the check, we collect all the views in the entity view container to the dictionary
                // if the views are changed then we will throw exception out
                if (this.VerifyViewsHaveNotChanged(workspace, entityViewContainer))
                {
                    this.SerializedAddGeneratedViews(workspace, entityViewContainer, extentMappingViews);
                }
                else
                {
                    throw new InvalidOperationException(System.Data.Entity.Strings.Generated_Views_Changed);
                }
            }
Exemplo n.º 9
0
        private bool IsComplexType(Type clrType)
        {
            MetadataWorkspace    metadataWorkspace    = this.GetObjectContextWithoutDatabaseInitialization().MetadataWorkspace;
            ObjectItemCollection objectItemCollection = (ObjectItemCollection)metadataWorkspace.GetItemCollection(DataSpace.OSpace);

            return(metadataWorkspace.GetItems <ComplexType>(DataSpace.OSpace).Any <ComplexType>((Func <ComplexType, bool>)(t => objectItemCollection.GetClrType((StructuralType)t) == clrType)));
        }
 internal static IEnumerable <EdmType> GetTypeAndSubtypesOf(
     EdmType type,
     MetadataWorkspace workspace,
     bool includeAbstractTypes)
 {
     return(MetadataHelper.GetTypeAndSubtypesOf(type, workspace.GetItemCollection(DataSpace.CSpace), includeAbstractTypes));
 }
Exemplo n.º 11
0
        private void ExtractTableColumnEdmMembers()
        {
            IEnumerable <object> entitySetMaps =
                (IEnumerable <object>)_metadataWorkspace
                .GetItemCollection(DataSpace.CSSpace)[0]
                .GetPrivateFieldValue("EntitySetMaps");

            foreach (var entitySetMap in entitySetMaps)
            {
                IEnumerable <object> typeMappings = (IEnumerable <object>)entitySetMap.GetPrivateFieldValue("TypeMappings");
                foreach (var typeMapping in typeMappings)
                {
                    IEnumerable <EdmType> types = (IEnumerable <EdmType>)typeMapping.GetPrivateFieldValue("Types");
                    foreach (EntityType type in types)
                    {
                        string identity = type.FullName;

                        List <EdmMember> properties = new List <EdmMember>(type.Properties);
                        properties.AddRange(type.NavigationProperties);

                        _tableColumnEdmMembers[identity] = properties;
                    }
                }
            }
        }
Exemplo n.º 12
0
        public OeEf6EdmModelMetadataProvider(DbContext dbContext)
        {
            MetadataWorkspace workspace = ((IObjectContextAdapter)dbContext).ObjectContext.MetadataWorkspace;
            var itemCollection          = (ObjectItemCollection)workspace.GetItemCollection(DataSpace.OSpace);

            _entityTypes = workspace.GetItems <EntityType>(DataSpace.CSpace).ToDictionary(e => itemCollection.GetClrType(workspace.GetObjectSpaceType(e)));
        }
Exemplo n.º 13
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);
        }
        // refs:
        // * http://romiller.com/2014/04/08/ef6-1-mapping-between-types-tables/
        // * http://blogs.msdn.com/b/appfabriccat/archive/2010/10/22/metadataworkspace-reference-in-wcf-services.aspx
        // * http://msdn.microsoft.com/en-us/library/system.data.metadata.edm.dataspace.aspx - describes meaning of OSpace etc
        // * http://stackoverflow.com/questions/22999330/mapping-from-iedmentity-to-clr

        internal IList <EnumReference> FindEnumReferences(MetadataWorkspace metadataWorkspace)
        {
            // Get the part of the model that contains info about the actual CLR types
            var objectItemCollection = ((ObjectItemCollection)metadataWorkspace.GetItemCollection(DataSpace.OSpace));
            // OSpace = Object Space

            var entities = metadataWorkspace.GetItems <EntityType>(DataSpace.OSpace);

            // find and return all the references to enum types
            var references = new List <EnumReference>();

            foreach (var entityType in entities)
            {
                var mappingFragment = FindSchemaMappingFragment(metadataWorkspace, entityType);

                // child types in TPH don't get mappings
                if (mappingFragment == null)
                {
                    continue;
                }

                references.AddRange(ProcessEdmProperties(entityType.Properties, mappingFragment, objectItemCollection));
            }
            return(references);
        }
Exemplo n.º 15
0
        public void TestMetadataWorkspace()
        {
            var asm     = Assembly.GetExecutingAssembly();
            var asmType = asm.GetType();

            Console.WriteLine(asmType.Name);
            var workspace =
                new MetadataWorkspace(
                    new[]
            {
                @".\Model\Data\DataModel.csdl",
                @".\Model\Data\DataModel.ssdl",
                @".\Model\Data\DataModel.msl"
            }, new[] { asm });

            foreach (var item in workspace.GetItemCollection(DataSpace.CSSpace))
            {
                Console.WriteLine(item.ToString());
            }

            const string assemblyQualifiedName = @"Intersoft.CISSA.DataAccessLayer";
            Type         anyModelType          = Type.GetType(assemblyQualifiedName);

            Console.WriteLine(anyModelType != null ? anyModelType.Name : "----");
            if (anyModelType != null)
            {
                Assembly modelAssembly = Assembly.GetAssembly(anyModelType);
                Console.WriteLine(modelAssembly.FullName);
            }

            foreach (var refAssembly in asm.GetReferencedAssemblies())
            {
                Console.WriteLine(refAssembly.Name);
            }
        }
            public void Registering_c_space_causes_oc_mapping_to_also_be_registered_if_it_is_not_already_registered()
            {
                var edmItemCollection = new EdmItemCollection(new[] { XDocument.Parse(Csdl).CreateReader() });

                var workspace = new MetadataWorkspace();

#pragma warning disable 612,618
                workspace.RegisterItemCollection(edmItemCollection);
#pragma warning restore 612,618

                Assert.Same(edmItemCollection, workspace.GetItemCollection(DataSpace.CSpace));

                var ocMappingCollection = (DefaultObjectMappingItemCollection)workspace.GetItemCollection(DataSpace.OCSpace);
                Assert.Same(workspace.GetItemCollection(DataSpace.OSpace), ocMappingCollection.ObjectItemCollection);
                Assert.Same(edmItemCollection, ocMappingCollection.EdmItemCollection);
            }
Exemplo n.º 17
0
        internal static Type GetClrType(MetadataWorkspace ocWorkspace, EnumType edmType)
        {
            var oSpaceType           = (EnumType)ocWorkspace.GetObjectSpaceType(edmType);
            var objectItemCollection = (ObjectItemCollection)(ocWorkspace.GetItemCollection(DataSpace.OSpace));

            return(objectItemCollection.GetClrType(oSpaceType));
        }
        internal static IDbExecutionStrategy GetExecutionStrategy(
            DbConnection connection,
            MetadataWorkspace metadataWorkspace)
        {
            StoreItemCollection itemCollection = (StoreItemCollection)metadataWorkspace.GetItemCollection(DataSpace.SSpace);

            return(DbProviderServices.GetExecutionStrategy(connection, itemCollection.ProviderFactory, (string)null));
        }
Exemplo n.º 19
0
        public void RegisterFactoryForWorkspace(MetadataWorkspace metadataWorkspace)
        {
            var storageMappingItemCollection = (StorageMappingItemCollection)metadataWorkspace.GetItemCollection(DataSpace.CSSpace);

            storageMappingItemCollection.MappingViewCacheFactory = this;

            _logger.Trace(() => $"Registered {nameof(EfMappingViewCacheFactory)} to {nameof(MetadataWorkspace)}.");
        }
        /// <summary>
        ///     Gets the <see cref="IExecutionStrategy" /> that will be used to execute methods that use the specified connection.
        ///     Uses MetadataWorkspace for faster lookup.
        /// </summary>
        /// <param name="connection">The database connection</param>
        /// <returns>
        ///     A new instance of <see cref="ExecutionStrategyBase" />
        /// </returns>
        internal static IExecutionStrategy GetExecutionStrategy(
            DbConnection connection,
            MetadataWorkspace metadataWorkspace)
        {
            var storeMetadata = (StoreItemCollection)metadataWorkspace.GetItemCollection(DataSpace.SSpace);

            return(GetExecutionStrategy(connection, storeMetadata.StoreProviderFactory));
        }
Exemplo n.º 21
0
        public static Type GetTypeFromName(this MetadataWorkspace metadata, string entityName)
        {
            var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace));

            return(objectItemCollection
                   .GetItems <EntityType>()
                   .Select(i => objectItemCollection.GetClrType(i))
                   .SingleOrDefault(t => t.Name == entityName));
        }
Exemplo n.º 22
0
        private Type GetNavigationTargetType(NavigationProperty navigationProperty)
        {
            MetadataWorkspace metadataWorkspace = this._internalContext.ObjectContext.MetadataWorkspace;

            System.Data.Entity.Core.Metadata.Edm.EntityType entityType = navigationProperty.RelationshipType.RelationshipEndMembers.Single <RelationshipEndMember>((Func <RelationshipEndMember, bool>)(e => navigationProperty.ToEndMember.Name == e.Name)).GetEntityType();
            StructuralType objectSpaceType = metadataWorkspace.GetObjectSpaceType((StructuralType)entityType);

            return(((ObjectItemCollection)metadataWorkspace.GetItemCollection(DataSpace.OSpace)).GetClrType(objectSpaceType));
        }
        public static EntityType GetObjectSpaceEntityByType <T>(this MetadataWorkspace metadataWorkspace)
        {
            ObjectItemCollection objectItemCollection = (ObjectItemCollection)metadataWorkspace.GetItemCollection(DataSpace.OSpace);

            EntityType entityType = objectItemCollection.GetItems <EntityType>()
                                    .FirstOrDefault(x => objectItemCollection.GetClrType(x) == typeof(T));

            return(entityType);
        }
        public static AssociationType ForeignKeyFor(this DbContext context, Type source, Type target)
        {
            MetadataWorkspace  metadata             = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace;
            ItemCollection     objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace));
            EntityType         sourceItem           = objectItemCollection.Where(o => o is EntityType && ((EntityType)o).GetReferenceType().ElementType.FullName == GetBaseTypeFor(source).FullName).FirstOrDefault() as EntityType;
            NavigationProperty property             = (sourceItem as EntityType).NavigationProperties.Where(p => ((p.ToEndMember.MetadataProperties["TypeUsage"].Value as TypeUsage).EdmType.MetadataProperties["ElementType"].Value as EntityType).FullName == GetBaseTypeFor(target).FullName).FirstOrDefault();

            return(metadata.GetItems <AssociationType>(DataSpace.CSpace).FirstOrDefault(a => a.IsForeignKey && a.ReferentialConstraints[0].ToRole.Name.Equals(property.FromEndMember.Name) && a.ReferentialConstraints[0].FromRole.Name.Equals(property.ToEndMember.Name)));
        }
Exemplo n.º 25
0
        private static EntityType getObjectType(MetadataWorkspace metadata, System.Type entityType)
        {
            var objectItemCollection = (ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace);

            var edmEntityType = metadata
                                .GetItems <EntityType>(DataSpace.OSpace)
                                .First(e => objectItemCollection.GetClrType(e) == entityType);

            return(edmEntityType);
        }
Exemplo n.º 26
0
        public static IEnumerable <Type> GetEntityTypes(this MetadataWorkspace metadata)
        {
            var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace));

            var entityTypes = objectItemCollection
                              .GetItems <EntityType>()
                              .Select(i => objectItemCollection.GetClrType(i));

            return(entityTypes);
        }
Exemplo n.º 27
0
        private static Type GetClrType(
            MetadataWorkspace workspace,
            StructuralType edmType)
        {
            StructuralType oSpaceType = workspace
                                        .GetItem <StructuralType>(edmType.FullName, DataSpace.OSpace);

            ObjectItemCollection objectItems =
                workspace.GetItemCollection(DataSpace.OSpace) as ObjectItemCollection;

            return(objectItems.GetClrType(oSpaceType));
        }
Exemplo n.º 28
0
        internal static DbSpatialDataReader CreateSpatialDataReader(MetadataWorkspace workspace, DbDataReader reader)
        {
            StoreItemCollection storeItemCollection = (StoreItemCollection)workspace.GetItemCollection(DataSpace.SSpace);
            DbProviderFactory providerFactory = storeItemCollection.StoreProviderFactory;
            Debug.Assert(providerFactory != null, "GetProviderSpatialServices requires provider factory to have been initialized");

            DbProviderServices providerServices = DbProviderServices.GetProviderServices(providerFactory);
            DbSpatialDataReader result = providerServices.GetSpatialDataReader(reader, storeItemCollection.StoreProviderManifestToken);
            Debug.Assert(result != null, "DbProviderServices did not throw ProviderIncompatibleException for null IDbSpatialDataReader");

            return result;
        }
Exemplo n.º 29
0
        public static string[] GetPrimaryKeys(this MetadataWorkspace metadata, Type entityType)
        {
            // Get the mapping between CLR types and metadata OSpace
            var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace));

            // Get metadata for given CLR type
            var entityMetadata = metadata
                                 .GetItems <EntityType>(DataSpace.OSpace)
                                 .Single(e => objectItemCollection.GetClrType(e) == entityType);

            return(entityMetadata.KeyProperties.Select(p => p.Name).ToArray());
        }
            public void Three_delegates_constructor_uses_given_delegates_and_sets_up_default_o_space_and_oc_mapping()
            {
                var edmItemCollection = new EdmItemCollection(new[] { XDocument.Parse(_csdlV3).CreateReader() });
                var storeItemCollection = new StoreItemCollection(new[] { XDocument.Parse(_ssdlV3).CreateReader() });
                var storageMappingItemCollection = LoadMsl(edmItemCollection, storeItemCollection);

                var workspace = new MetadataWorkspace(
                    () => edmItemCollection,
                    () => storeItemCollection,
                    () => storageMappingItemCollection);

                Assert.Same(edmItemCollection, workspace.GetItemCollection(DataSpace.CSpace));
                Assert.Same(storeItemCollection, workspace.GetItemCollection(DataSpace.SSpace));
                Assert.Same(storageMappingItemCollection, workspace.GetItemCollection(DataSpace.CSSpace));

                var objectItemCollection = (ObjectItemCollection)workspace.GetItemCollection(DataSpace.OSpace);
                var ocMappingCollection = (DefaultObjectMappingItemCollection)workspace.GetItemCollection(DataSpace.OCSpace);

                Assert.Same(objectItemCollection, ocMappingCollection.ObjectItemCollection);
                Assert.Same(edmItemCollection, ocMappingCollection.EdmItemCollection);
            }
Exemplo n.º 31
0
        internal static IEnumerable <AssociationType> GetAllRelationshipsForType(MetadataWorkspace workspace, Type clrType)
        {
            DebugCheck.NotNull(workspace);
            DebugCheck.NotNull(clrType);

            // Note that this gets any relationship that the CLR type participates in in any entity set. For MEST, this
            // could result in too many relationships being returned, but this doesn't matter since the extra ones will
            // not be used. Also, MEST is rare.
            return(((ObjectItemCollection)workspace.GetItemCollection(DataSpace.OSpace)).GetItems <AssociationType>().Where(
                       a => IsEndMemberForType(a.AssociationEndMembers[0], clrType) ||
                       IsEndMemberForType(a.AssociationEndMembers[1], clrType)));
        }
            public void Three_delegates_constructor_uses_given_delegates_and_sets_up_default_o_space_and_oc_mapping()
            {
                var edmItemCollection            = new EdmItemCollection(new[] { XDocument.Parse(Csdl).CreateReader() });
                var storeItemCollection          = new StoreItemCollection(new[] { XDocument.Parse(Ssdl).CreateReader() });
                var storageMappingItemCollection = LoadMsl(edmItemCollection, storeItemCollection);

                var workspace = new MetadataWorkspace(
                    () => edmItemCollection,
                    () => storeItemCollection,
                    () => storageMappingItemCollection);

                Assert.Same(edmItemCollection, workspace.GetItemCollection(DataSpace.CSpace));
                Assert.Same(storeItemCollection, workspace.GetItemCollection(DataSpace.SSpace));
                Assert.Same(storageMappingItemCollection, workspace.GetItemCollection(DataSpace.CSSpace));

                var objectItemCollection = (ObjectItemCollection)workspace.GetItemCollection(DataSpace.OSpace);
                var ocMappingCollection  = (DefaultObjectMappingItemCollection)workspace.GetItemCollection(DataSpace.OCSpace);

                Assert.Same(objectItemCollection, ocMappingCollection.ObjectItemCollection);
                Assert.Same(edmItemCollection, ocMappingCollection.EdmItemCollection);
            }
Exemplo n.º 33
0
 private static IEnumerable <EntitySet> GetModelTables(MetadataWorkspace workspace)
 {
     return(workspace
            .GetItemCollection(DataSpace.SSpace)
            .GetItems <EntityContainer>()
            .Single()
            .BaseEntitySets
            .OfType <EntitySet>()
            .Where(
                s => !s.MetadataProperties.Contains("Type") ||
                (string)s.MetadataProperties["Type"].Value == "Tables"));
 }
            public void GetItemCollection_on_both_C_and_S_space_using_item_collections_with_inconsistent_versions_throws_MetadataException()
            {
                var edmItemCollection   = new EdmItemCollection(new[] { XDocument.Parse(_csdlV3).CreateReader() });
                var storeItemCollection =
                    new StoreItemCollection(
                        new[]
                {
                    XDocument.Parse(string.Format(CultureInfo.InvariantCulture, SsdlTemplate, XmlConstants.TargetNamespace_2))
                    .CreateReader()
                });

                var workspace = new MetadataWorkspace(
                    () => edmItemCollection,
                    () => storeItemCollection,
                    () => null);

                workspace.GetItemCollection(DataSpace.CSpace); // this sets up the MetadataWorkspace's expected schema version as the csdl version i.e. 3.0
                Assert.Equal(
                    Resources.Strings.DifferentSchemaVersionInCollection("StoreItemCollection", 2.0, 3.0),
                    Assert.Throws <MetadataException>(() => workspace.GetItemCollection(DataSpace.SSpace)).Message);
            }
        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);
        }
Exemplo n.º 36
0
        public static EntityContainer GetEntityContainer(MetadataWorkspace workspace)
        {
            // Get the Storage Schema Definition
            ItemCollection ssdl = workspace.GetItemCollection(DataSpace.SSpace);

            EntityContainer entityContainer = ssdl.OfType<EntityContainer>().FirstOrDefault();

            if (entityContainer == null)
            {
                // Invalid SSDL
                throw new InvalidOperationException("The Storage Schema Definition does not contain any EntityContainer");
            }

            return entityContainer;
        }
Exemplo n.º 37
0
        internal static DbSpatialDataReader CreateSpatialDataReader(MetadataWorkspace workspace, DbDataReader reader)
        {
            var storeItemCollection = (StoreItemCollection)workspace.GetItemCollection(DataSpace.SSpace);
            var providerFactory = storeItemCollection.ProviderFactory;
            Debug.Assert(providerFactory != null, "GetProviderSpatialServices requires provider factory to have been initialized");

            var providerServices = providerFactory.GetProviderServices();
            var result = providerServices.GetSpatialDataReader(reader, storeItemCollection.ProviderManifestToken);

            if (result == null)
            {
                throw new ProviderIncompatibleException(Strings.ProviderDidNotReturnSpatialServices);
            }

            return result;
        }
        public static MetadataWorkspace ToMetadataWorkspace(this DbDatabaseMapping databaseMapping)
        {
            DebugCheck.NotNull(databaseMapping);

            var itemCollection = new EdmItemCollection(databaseMapping.Model);
            var storeItemCollection = new StoreItemCollection(databaseMapping.Database);
            var storageMappingItemCollection = databaseMapping.ToStorageMappingItemCollection(itemCollection, storeItemCollection);

            var workspace = new MetadataWorkspace(
                () => itemCollection,
                () => storeItemCollection,
                () => storageMappingItemCollection);

            new CodeFirstOSpaceLoader().LoadTypes(itemCollection, (ObjectItemCollection)workspace.GetItemCollection(DataSpace.OSpace));

            return workspace;
        }
Exemplo n.º 39
0
		// refs:
		// * http://romiller.com/2014/04/08/ef6-1-mapping-between-types-tables/
		// * http://blogs.msdn.com/b/appfabriccat/archive/2010/10/22/metadataworkspace-reference-in-wcf-services.aspx
		// * http://msdn.microsoft.com/en-us/library/system.data.metadata.edm.dataspace.aspx - describes meaning of OSpace etc
		// * http://stackoverflow.com/questions/22999330/mapping-from-iedmentity-to-clr

		internal IList<EnumReference> FindEnumReferences(MetadataWorkspace metadataWorkspace)
		{
			// Get the part of the model that contains info about the actual CLR types
			var objectItemCollection = ((ObjectItemCollection)metadataWorkspace.GetItemCollection(DataSpace.OSpace));
			// OSpace = Object Space

			var entities = metadataWorkspace.GetItems<EntityType>(DataSpace.OSpace);

			// find and return all the references to enum types
			var references = new List<EnumReference>();
			foreach (var entityType in entities)
			{
				var mappingFragment = FindSchemaMappingFragment(metadataWorkspace, entityType);

				// child types in TPH don't get mappings
				if (mappingFragment == null)
				{
					continue;
				}

				references.AddRange(ProcessEdmProperties(entityType.Properties, mappingFragment, objectItemCollection));
			}
			return references;
		}
        /// <summary>
        /// Requires: a public type with a public, default constructor. Returns a column map initializing the type
        /// and all properties of the type with a public setter taking a primitive type and having a corresponding 
        /// column in the reader.
        /// </summary>
        internal static CollectionColumnMap CreateColumnMapFromReaderAndClrType(DbDataReader reader, Type type, MetadataWorkspace workspace)
        {
            Debug.Assert(null != reader);
            Debug.Assert(null != type);
            Debug.Assert(null != workspace);

            // we require a default constructor
            ConstructorInfo constructor = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
                null, Type.EmptyTypes, null);
            if (type.IsAbstract || (null == constructor && !type.IsValueType))
            {
                throw EntityUtil.InvalidOperation(
                    Strings.ObjectContext_InvalidTypeForStoreQuery(type));
            }

            // build a LINQ expression used by result assembly to create results
            var memberInfo = new List<Tuple<MemberAssignment, int, EdmProperty>>();
            foreach (PropertyInfo prop in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                // for enums unwrap the type if nullable
                var propertyUnderlyingType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
                Type propType = propertyUnderlyingType.IsEnum ? propertyUnderlyingType.GetEnumUnderlyingType() : prop.PropertyType;

                EdmType modelType;
                int ordinal;
                if (TryGetColumnOrdinalFromReader(reader, prop.Name, out ordinal) &&
                    MetadataHelper.TryDetermineCSpaceModelType(propType, workspace, out modelType) &&
                    (Helper.IsScalarType(modelType)) &&
                    prop.CanWrite && prop.GetIndexParameters().Length == 0 && null != prop.GetSetMethod(/* nonPublic */true))
                {
                    memberInfo.Add(Tuple.Create(
                        Expression.Bind(prop, Expression.Parameter(prop.PropertyType, "placeholder")),
                        ordinal,
                        new EdmProperty(prop.Name, TypeUsage.Create(modelType))));
                }
            }
            // initialize members in the order in which they appear in the reader
            MemberInfo[] members = new MemberInfo[memberInfo.Count];
            MemberBinding[] memberBindings = new MemberBinding[memberInfo.Count];
            ColumnMap[] propertyMaps = new ColumnMap[memberInfo.Count];
            EdmProperty[] modelProperties = new EdmProperty[memberInfo.Count];
            int i = 0;
            foreach (var memberGroup in memberInfo.GroupBy(tuple => tuple.Item2).OrderBy(tuple => tuple.Key))
            {
                // make sure that a single column isn't contributing to multiple properties
                if (memberGroup.Count() != 1)
                {
                    throw EntityUtil.InvalidOperation(Strings.ObjectContext_TwoPropertiesMappedToSameColumn(
                        reader.GetName(memberGroup.Key), 
                        String.Join(", ", memberGroup.Select(tuple => tuple.Item3.Name).ToArray())));
                }

                var member = memberGroup.Single();
                MemberAssignment assignment = member.Item1;
                int ordinal = member.Item2;
                EdmProperty modelProp = member.Item3;
                
                members[i] = assignment.Member;
                memberBindings[i] = assignment;
                propertyMaps[i] = new ScalarColumnMap(modelProp.TypeUsage, modelProp.Name, 0, ordinal);
                modelProperties[i] = modelProp;
                i++;
            }
            NewExpression newExpr = null == constructor ? Expression.New(type) : Expression.New(constructor);
            MemberInitExpression init = Expression.MemberInit(newExpr, memberBindings);
            InitializerMetadata initMetadata = InitializerMetadata.CreateProjectionInitializer(
                (EdmItemCollection)workspace.GetItemCollection(DataSpace.CSpace), init, members);

            // column map (a collection of rows with InitializerMetadata markup)
            RowType rowType = new RowType(modelProperties, initMetadata);
            RecordColumnMap rowMap = new RecordColumnMap(TypeUsage.Create(rowType),
                "DefaultTypeProjection", propertyMaps, null);
            CollectionColumnMap collectionMap = new SimpleCollectionColumnMap(rowType.GetCollectionType().TypeUsage, 
                rowType.Name, rowMap, null, null);
            return collectionMap;
        }
            public void Registering_c_space_or_o_space_does_not_cause_oc_mapping_to_be_registered_if_it_is_already_registered()
            {
                var edmItemCollection = new EdmItemCollection(new[] { XDocument.Parse(Csdl).CreateReader() });
                var objectItemCollection = new ObjectItemCollection();
                var ocMappingItemCollection = new DefaultObjectMappingItemCollection(edmItemCollection, objectItemCollection);

                var workspace = new MetadataWorkspace();
#pragma warning disable 612,618
                workspace.RegisterItemCollection(ocMappingItemCollection);
                workspace.RegisterItemCollection(edmItemCollection);
                workspace.RegisterItemCollection(objectItemCollection);
#pragma warning restore 612,618

                Assert.Same(ocMappingItemCollection, workspace.GetItemCollection(DataSpace.OCSpace));
                Assert.Same(edmItemCollection, workspace.GetItemCollection(DataSpace.CSpace));
                Assert.Same(objectItemCollection, workspace.GetItemCollection(DataSpace.OSpace));
            }
            private static bool VerifyViewsHaveNotChanged(MetadataWorkspace workspace, EntityViewContainer viewContainer)
            {
                //Now check whether the hash of the generated views match the one
                //we stored in the code file during design
                //Produce the hash and add it to the code
                var mappingCollection = (workspace.GetItemCollection(DataSpace.CSSpace) as StorageMappingItemCollection);
                Debug.Assert(mappingCollection != null, "Must have Mapping Collection in the Metadataworkspace");

                var viewHash = MetadataHelper.GenerateHashForAllExtentViewsContent(
                    mappingCollection.MappingVersion, viewContainer.ExtentViews);
                var storedViewHash = viewContainer.HashOverAllExtentViews;
                if (viewHash != storedViewHash)
                {
                    return false;
                }
                return true;
            }
Exemplo n.º 43
0
        /// <summary>
        /// Constructs the EntityConnection from Metadata loaded in memory
        /// </summary>
        /// <param name="workspace">Workspace containing metadata information.</param>
        public EntityConnection(MetadataWorkspace workspace, DbConnection connection)
        {
            GC.SuppressFinalize(this);

            EntityUtil.CheckArgumentNull(workspace, "workspace");
            EntityUtil.CheckArgumentNull(connection, "connection");
            

            if (!workspace.IsItemCollectionAlreadyRegistered(DataSpace.CSpace))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.EntityClient_ItemCollectionsNotRegisteredInWorkspace("EdmItemCollection"));
            }
            if(!workspace.IsItemCollectionAlreadyRegistered(DataSpace.SSpace))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.EntityClient_ItemCollectionsNotRegisteredInWorkspace("StoreItemCollection"));
            }
            if(!workspace.IsItemCollectionAlreadyRegistered(DataSpace.CSSpace))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.EntityClient_ItemCollectionsNotRegisteredInWorkspace("StorageMappingItemCollection"));
            }

            if (connection.State != ConnectionState.Closed)
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.EntityClient_ConnectionMustBeClosed);
            }

            // Verify that a factory can be retrieved
            if (DbProviderFactories.GetFactory(connection) == null)
            {
                throw EntityUtil.ProviderIncompatible(System.Data.Entity.Strings.EntityClient_DbConnectionHasNoProvider(connection));
            }

            StoreItemCollection collection = (StoreItemCollection)workspace.GetItemCollection(DataSpace.SSpace);

            _providerFactory = collection.StoreProviderFactory;
            _storeConnection = connection;
            _userOwnsStoreConnection = true;
            _metadataWorkspace = workspace;
            _initialized = true;
        }
Exemplo n.º 44
0
        private static void SetupFooFunction(MetadataWorkspace metadataWorkspace)
        {
            var metadataWorkspaceMock = Mock.Get(metadataWorkspace);
            var entityType = (EdmType)new EntityType(
                                          "ReturnedEntity", "FooNamespace", DataSpace.CSpace,
                                          new[] { "key" }, new EdmMember[] { new EdmProperty("key") });
            var collectionTypeMock = new Mock<CollectionType>(entityType)
            {
                CallBase = true
            };
            metadataWorkspaceMock.Setup(m => m.TryDetermineCSpaceModelType(It.IsAny<Type>(), out entityType))
                                 .Returns(true);

            var entityContainer = new EntityContainer("Bar", DataSpace.CSpace);
            metadataWorkspaceMock.Setup(m => m.TryGetEntityContainer(It.IsAny<string>(), It.IsAny<DataSpace>(), out entityContainer))
                                 .Returns(true);
            var functionImport = new EdmFunction(
                "Foo", "Bar", DataSpace.CSpace,
                new EdmFunctionPayload
                {
                    IsComposable = false,
                    IsFunctionImport = true,
                    ReturnParameters = new[]
                                {
                                    new FunctionParameter(
                                        EdmConstants.ReturnType,
                                        TypeUsage.Create(collectionTypeMock.Object),
                                        ParameterMode.ReturnValue),
                                }
                });
            entityContainer.AddFunctionImport(functionImport);

            entityContainer.AddEntitySetBase(new EntitySet("Foo", "", "", "", (EntityType)entityType));

            var edmItemCollection = (EdmItemCollection)metadataWorkspace.GetItemCollection(DataSpace.CSpace);
            var storeItemCollection = (StoreItemCollection)metadataWorkspace.GetItemCollection(DataSpace.SSpace);
            var containerMappingMock = new Mock<EntityContainerMapping>(entityContainer);
            FunctionImportMapping targetFunctionMapping = new FunctionImportMappingNonComposable(
                functionImport, functionImport, new List<List<FunctionImportStructuralTypeMapping>>(), edmItemCollection);
            containerMappingMock.Setup(
                m => m.TryGetFunctionImportMapping(
                    It.IsAny<EdmFunction>(), out targetFunctionMapping)).Returns(true);

            var storageMappingItemCollection = new Mock<StorageMappingItemCollection>(
                edmItemCollection, storeItemCollection, new string[0])
            {
                CallBase = true
            };
            storageMappingItemCollection.Setup(m => m.GetItems<EntityContainerMapping>())
                                        .Returns(
                                            new ReadOnlyCollection<EntityContainerMapping>(
                                                new List<EntityContainerMapping>
                                                        {
                                                            containerMappingMock.Object
                                                        }));

            metadataWorkspaceMock.Setup(m => m.GetItemCollection(DataSpace.CSSpace, It.IsAny<bool>()))
                                 .Returns(storageMappingItemCollection.Object);
        }
            public void GetItemCollection_on_both_CS_and_S_space_using_item_collections_with_inconsistent_versions_throws_MetadataException()
            {
                var edmItemCollection = new EdmItemCollection(new[] { XDocument.Parse(_csdlV3).CreateReader() });
                var storeItemCollection = new StoreItemCollection(new[] { XDocument.Parse(_ssdlV3).CreateReader() });
                var storageMappingItemCollection = LoadMsl(edmItemCollection, storeItemCollection);

                // edmItemCollection and storeItemCollection must have the same version to generate storageMappingItemCollection
                // here we override the storeItemCollection so that it's version will be different for the MetadataWorkspace
                storeItemCollection =
                    new StoreItemCollection(
                        new[]
                            {
                                XDocument.Parse(string.Format(CultureInfo.InvariantCulture, SsdlTemplate, XmlConstants.TargetNamespace_2))
                                    .CreateReader()
                            });

                var workspace = new MetadataWorkspace(
                    () => null,
                    () => storeItemCollection,
                    () => storageMappingItemCollection);

                workspace.GetItemCollection(DataSpace.SSpace); // this sets up the MetadataWorkspace's expected schema version as the ssdl version i.e. 2.0
                Assert.Equal(
                    Resources.Strings.DifferentSchemaVersionInCollection("StorageMappingItemCollection", 3.0, 2.0),
                    Assert.Throws<MetadataException>(() => workspace.GetItemCollection(DataSpace.CSSpace)).Message);
            }
        internal static IEnumerable<AssociationType> GetAllRelationshipsForType(MetadataWorkspace workspace, Type clrType)
        {
            DebugCheck.NotNull(workspace);
            DebugCheck.NotNull(clrType);

            // Note that this gets any relationship that the CLR type participates in in any entity set. For MEST, this
            // could result in too many relationships being returned, but this doesn't matter since the extra ones will
            // not be used. Also, MEST is rare.
            return ((ObjectItemCollection)workspace.GetItemCollection(DataSpace.OSpace)).GetItems<AssociationType>().Where(
                a => IsEndMemberForType(a.AssociationEndMembers[0], clrType)
                     || IsEndMemberForType(a.AssociationEndMembers[1], clrType));
        }
            public void Paths_constructor_loads_collections_from_given_paths_and_sets_up_o_space_and_oc_mapping()
            {
                RunTestWithTempMetadata(
                    _csdlV3, _ssdlV3, _mslV3,
                    paths =>
                        {
                            var workspace = new MetadataWorkspace(paths, new Assembly[0]);

                            var cSpace = (EdmItemCollection)workspace.GetItemCollection(DataSpace.CSpace);
                            Assert.NotNull(cSpace.GetType("Entity", "AdventureWorksModel"));

                            var sSpace = (StoreItemCollection)workspace.GetItemCollection(DataSpace.SSpace);
                            Assert.NotNull(sSpace.GetType("Entities", "AdventureWorksModel.Store"));

                            var csMapping = (StorageMappingItemCollection)workspace.GetItemCollection(DataSpace.CSSpace);
                            Assert.Same(cSpace, csMapping.EdmItemCollection);
                            Assert.Same(sSpace, csMapping.StoreItemCollection);

                            var oSpace = (ObjectItemCollection)workspace.GetItemCollection(DataSpace.OSpace);
                            var ocMapping = (DefaultObjectMappingItemCollection)workspace.GetItemCollection(DataSpace.OCSpace);
                            Assert.Same(oSpace, ocMapping.ObjectItemCollection);
                            Assert.Same(cSpace, ocMapping.EdmItemCollection);
                        });
            }
        /// <summary>
        ///     Gets the <see cref="IExecutionStrategy" /> that will be used to execute methods that use the specified connection.
        ///     Uses MetadataWorkspace for faster lookup.
        /// </summary>
        /// <param name="connection">The database connection</param>
        /// <returns>
        ///     A new instance of <see cref="ExecutionStrategyBase" />
        /// </returns>
        internal static IExecutionStrategy GetExecutionStrategy(
            DbConnection connection,
            MetadataWorkspace metadataWorkspace)
        {
            var storeMetadata = (StoreItemCollection)metadataWorkspace.GetItemCollection(DataSpace.SSpace);

            return GetExecutionStrategy(connection, storeMetadata.StoreProviderFactory);
        }
        public void O_space_types_are_discovered_when_using_attribute_based_mapping()
        {
            var edmItemCollection = new EdmItemCollection(
                new[]
                    {
                        XDocument.Load(
                            typeof(AttributeBasedOCLoading).Assembly.GetManifestResourceStream(
                                "System.Data.Entity.TestModels.TemplateModels.Schemas.MonsterModel.csdl")).CreateReader()
                    });

            var storeItemCollection = new StoreItemCollection(
                new[]
                    {
                        XDocument.Load(
                            typeof(AttributeBasedOCLoading).Assembly.GetManifestResourceStream(
                                "System.Data.Entity.TestModels.TemplateModels.Schemas.MonsterModel.ssdl")).CreateReader()
                    });
            var storageMappingItemCollection = LoadMsl(
                edmItemCollection, storeItemCollection, XDocument.Load(
                    typeof(AttributeBasedOCLoading).Assembly.GetManifestResourceStream(
                        "System.Data.Entity.TestModels.TemplateModels.Schemas.MonsterModel.msl")));

            var workspace = new MetadataWorkspace(
                () => edmItemCollection,
                () => storeItemCollection,
                () => storageMappingItemCollection);

            var assembly = BuildEntitiesAssembly(ObjectLayer);
            workspace.LoadFromAssembly(assembly);

            var oSpaceItems = (ObjectItemCollection)workspace.GetItemCollection(DataSpace.OSpace);

            // Sanity checks that types/relationships were actually found
            // Entity types
            var entityTypes = oSpaceItems
                .OfType<EdmType>()
                .Where(i => i.BuiltInTypeKind == BuiltInTypeKind.EntityType)
                .ToList();

            Assert.Equal(
                new[]
                    {
                        "BackOrderLine2Mm", "BackOrderLineMm", "BarcodeDetailMm", "BarcodeMm", "ComplaintMm", "ComputerDetailMm",
                        "ComputerMm", "CustomerInfoMm", "CustomerMm", "DiscontinuedProductMm", "DriverMm", "IncorrectScanMm",
                        "LastLoginMm", "LicenseMm", "LoginMm", "MessageMm", "OrderLineMm", "OrderMm", "OrderNoteMm",
                        "OrderQualityCheckMm", "PageViewMm", "PasswordResetMm", "ProductDetailMm", "ProductMm", "ProductPageViewMm",
                        "ProductPhotoMm", "ProductReviewMm", "ProductWebFeatureMm", "ResolutionMm", "RSATokenMm", "SmartCardMm",
                        "SupplierInfoMm", "SupplierLogoMm", "SupplierMm", "SuspiciousActivityMm"
                    },
                entityTypes.Select(i => i.Name).OrderBy(n => n));

            Assert.True(entityTypes.All(e => e.NamespaceName == "BuildMonsterModel"));
            Assert.True(entityTypes.All(e => oSpaceItems.GetClrType((StructuralType)e).Assembly == assembly));

            // Complex types
            var complexTypes = oSpaceItems
                .OfType<EdmType>()
                .Where(i => i.BuiltInTypeKind == BuiltInTypeKind.ComplexType)
                .ToList();

            Assert.Equal(
                new[] { "AuditInfoMm", "ConcurrencyInfoMm", "ContactDetailsMm", "DimensionsMm", "PhoneMm" },
                complexTypes.Select(i => i.Name).OrderBy(n => n));

            Assert.True(complexTypes.All(e => e.NamespaceName == "BuildMonsterModel"));
            Assert.True(complexTypes.All(e => oSpaceItems.GetClrType((StructuralType)e).Assembly == assembly));

            // Enum types
            var enumTypes = oSpaceItems
                .OfType<EdmType>()
                .Where(i => i.BuiltInTypeKind == BuiltInTypeKind.EnumType)
                .ToList();

            Assert.Equal(
                new[] { "LicenseStateMm", "PhoneTypeMm" },
                enumTypes.Select(i => i.Name).OrderBy(n => n));

            Assert.True(enumTypes.All(e => e.NamespaceName == "BuildMonsterModel"));
            Assert.True(enumTypes.All(e => oSpaceItems.GetClrType((EnumType)e).Assembly == assembly));

            // Associations
            var associations = oSpaceItems
                .OfType<AssociationType>()
                .Where(i => i.BuiltInTypeKind == BuiltInTypeKind.AssociationType)
                .ToList();

            Assert.Equal(
                new[]
                    {
                        "Barcode_BarcodeDetail", "Barcode_IncorrectScanActual", "Barcode_IncorrectScanExpected", "Complaint_Resolution",
                        "Computer_ComputerDetail", "Customer_Complaints", "Customer_CustomerInfo", "Customer_Logins", "Customer_Orders",
                        "DiscontinuedProduct_Replacement", "Driver_License", "Husband_Wife", "LastLogin_SmartCard", "Login_LastLogin",
                        "Login_Orders", "Login_PageViews", "Login_PasswordResets", "Login_ReceivedMessages", "Login_RSAToken",
                        "Login_SentMessages", "Login_SmartCard", "Login_SuspiciousActivity", "Order_OrderLines", "Order_OrderNotes",
                        "Order_QualityCheck", "Product_Barcodes", "Product_OrderLines", "Product_ProductDetail", "Product_ProductPageViews",
                        "Product_ProductPhoto", "Product_ProductReview", "Products_Suppliers", "ProductWebFeature_ProductPhoto",
                        "ProductWebFeature_ProductReview", "Supplier_BackOrderLines", "Supplier_SupplierInfo", "Supplier_SupplierLogo"
                    },
                associations.Select(i => i.Name).OrderBy(n => n));

            Assert.True(associations.All(e => e.NamespaceName == "MonsterNamespace"));
        }
            /// <summary>
            ///     this method do the following check on the generated views in the EntityViewContainer, 
            ///     then add those views all at once to the dictionary
            ///     1. there should be one storeageEntityContainerMapping that has the same h
            ///     C side and S side names as the EnittyViewcontainer
            ///     2. Generate the hash for the storageEntityContainerMapping in the MM closure, 
            ///     and this hash should be the same in EntityViewContainer
            ///     3. Generate the hash for all of the view text in the EntityViewContainer and 
            ///     this hash should be the same as the stored on in the EntityViewContainer
            /// </summary>
            /// <param name="entityViewContainer"> </param>
            private void SerializedAddGeneratedViewsInEntityViewContainer(
                MetadataWorkspace workspace, EntityViewContainer entityViewContainer,
                Dictionary<EntitySetBase, GeneratedView> extentMappingViews)
            {
                StorageEntityContainerMapping storageEntityContainerMapping;
                // first check
                if (!TryGetCorrespondingStorageEntityContainerMapping(
                    entityViewContainer,
                    workspace.GetItemCollection(DataSpace.CSSpace).GetItems<StorageEntityContainerMapping>(),
                    out storageEntityContainerMapping))
                {
                    return;
                }

                // second check
                if (!SerializedVerifyHashOverMmClosure(storageEntityContainerMapping, entityViewContainer))
                {
                    throw new MappingException(
                        Strings.ViewGen_HashOnMappingClosure_Not_Matching(entityViewContainer.EdmEntityContainerName));
                }

                // third check, prior to the check, we collect all the views in the entity view container to the dictionary
                // if the views are changed then we will throw exception out
                if (VerifyViewsHaveNotChanged(workspace, entityViewContainer))
                {
                    SerializedAddGeneratedViews(workspace, entityViewContainer, extentMappingViews);
                }
                else
                {
                    throw new InvalidOperationException(System.Data.Entity.Resources.Strings.Generated_Views_Changed);
                }
            }
        /// <summary>Gets the CLR type mapped to the specified C-Space type.</summary>
        /// <param name="workspace">Workspace in which the type is defined.</param>
        /// <param name="edmType">C-Space type whose matching clr type needs to be looked up.</param>
        /// <returns>The resolved <see cref="Type"/> for the given <paramref name="edmType"/>.</returns>
        internal static Type GetClrTypeForCSpaceType(MetadataWorkspace workspace, StructuralType edmType)
        {
            Debug.Assert(workspace != null, "workspace != null");
            Debug.Assert(edmType != null, "edmType != null");
            Debug.Assert(
               edmType.BuiltInTypeKind == BuiltInTypeKind.EntityType || edmType.BuiltInTypeKind == BuiltInTypeKind.ComplexType,
               "Must be entityType or complexType");

            StructuralType ospaceType;
            if (workspace.TryGetObjectSpaceType(edmType, out ospaceType))
            {
                ObjectItemCollection objectItemCollection = (ObjectItemCollection)workspace.GetItemCollection(DataSpace.OSpace);
                return objectItemCollection.GetClrType(ospaceType);
            }

            return null;
        }
            /// <summary>
///     this method do the following check on the generated views in the EntityViewContainer,
///     then add those views all at once to the dictionary
///     1. there should be one storeageEntityContainerMapping that has the same h
///     C side and S side names as the EnittyViewcontainer
///     2. Generate the hash for the storageEntityContainerMapping in the MM closure,
///     and this hash should be the same in EntityViewContainer
///     3. Generate the hash for all of the view text in the EntityViewContainer and
///     this hash should be the same as the stored on in the EntityViewContainer
/// </summary>
/// <param name="entityViewContainer"> </param>
            private void SerializedAddGeneratedViewsInEntityViewContainer(
                MetadataWorkspace workspace, EntityViewContainer entityViewContainer,
                Dictionary<EntitySetBase, GeneratedView> extentMappingViews)
            {
                StorageEntityContainerMapping storageEntityContainerMapping;
                // first check
                if (!TryGetCorrespondingStorageEntityContainerMapping(
                    entityViewContainer,
                    workspace.GetItemCollection(DataSpace.CSSpace).GetItems<StorageEntityContainerMapping>(),
                    out storageEntityContainerMapping))
                {
                    return;
                }

                // second check
                if (!SerializedVerifyHashOverMmClosure(storageEntityContainerMapping, entityViewContainer))
                {
                    throw new MappingException(
                        Strings.ViewGen_HashOnMappingClosure_Not_Matching(entityViewContainer.EdmEntityContainerName));
                }

                SerializedAddGeneratedViews(workspace, entityViewContainer, extentMappingViews);
            }
            private static void Item_collections_can_be_registered(MetadataWorkspace workspace)
            {
                var edmItemCollection = new EdmItemCollection(new[] { XDocument.Parse(_csdlV3).CreateReader() });
                var storeItemCollection = new StoreItemCollection(new[] { XDocument.Parse(_ssdlV3).CreateReader() });
                var objectItemCollection = new ObjectItemCollection();
                var storageMappingItemCollection = LoadMsl(edmItemCollection, storeItemCollection);
                var ocMappingItemCollection = new DefaultObjectMappingItemCollection(edmItemCollection, objectItemCollection);

#pragma warning disable 612,618
                workspace.RegisterItemCollection(edmItemCollection);
                workspace.RegisterItemCollection(storeItemCollection);
                workspace.RegisterItemCollection(objectItemCollection);
                workspace.RegisterItemCollection(storageMappingItemCollection);
                workspace.RegisterItemCollection(ocMappingItemCollection);
#pragma warning restore 612,618

                Assert.Same(edmItemCollection, workspace.GetItemCollection(DataSpace.CSpace));
                Assert.Same(storeItemCollection, workspace.GetItemCollection(DataSpace.SSpace));
                Assert.Same(storageMappingItemCollection, workspace.GetItemCollection(DataSpace.CSSpace));
                Assert.Same(objectItemCollection, workspace.GetItemCollection(DataSpace.OSpace));
                Assert.Same(ocMappingItemCollection, workspace.GetItemCollection(DataSpace.OCSpace));
            }
Exemplo n.º 54
0
        // <summary>
        // This constructor allows to skip the initialization code for testing purposes.
        // </summary>
        internal EntityConnection(
            MetadataWorkspace workspace,
            DbConnection connection,
            bool skipInitialization,
            bool entityConnectionOwnsStoreConnection)
        {
            if (!skipInitialization)
            {
                if (!workspace.IsItemCollectionAlreadyRegistered(DataSpace.CSpace))
                {
                    throw new ArgumentException(Strings.EntityClient_ItemCollectionsNotRegisteredInWorkspace("EdmItemCollection"));
                }
                if (!workspace.IsItemCollectionAlreadyRegistered(DataSpace.SSpace))
                {
                    throw new ArgumentException(Strings.EntityClient_ItemCollectionsNotRegisteredInWorkspace("StoreItemCollection"));
                }
                if (!workspace.IsItemCollectionAlreadyRegistered(DataSpace.CSSpace))
                {
                    throw new ArgumentException(
                        Strings.EntityClient_ItemCollectionsNotRegisteredInWorkspace("StorageMappingItemCollection"));
                }

                // Verify that a factory can be retrieved
                var providerFactory = connection.GetProviderFactory();
                if (providerFactory == null)
                {
                    throw new ProviderIncompatibleException(Strings.EntityClient_DbConnectionHasNoProvider(connection));
                }

                var collection = (StoreItemCollection)workspace.GetItemCollection(DataSpace.SSpace);

                _providerFactory = collection.ProviderFactory;
                Debug.Assert(_providerFactory == providerFactory);
                _initialized = true;
            }

            _metadataWorkspace = workspace;
            _storeConnection = connection;
            _entityConnectionOwnsStoreConnection = entityConnectionOwnsStoreConnection;

            if (_storeConnection != null)
            {
                _entityClientConnectionState = DbInterception.Dispatch.Connection.GetState(_storeConnection, InterceptionContext);
            }

            SubscribeToStoreConnectionStateChangeEvents();
        }
                Registering_o_space_causes_oc_mapping_to_also_be_registered_if_it_is_not_already_registered_and_c_space_is_registered()
            {
                var edmItemCollection = new EdmItemCollection(new[] { XDocument.Parse(_csdlV3).CreateReader() });
                var objectItemCollection = new ObjectItemCollection();

                var workspace = new MetadataWorkspace();
#pragma warning disable 612,618
                workspace.RegisterItemCollection(edmItemCollection);
                workspace.RegisterItemCollection(objectItemCollection);
#pragma warning restore 612,618

                Assert.Same(edmItemCollection, workspace.GetItemCollection(DataSpace.CSpace));
                Assert.Same(objectItemCollection, workspace.GetItemCollection(DataSpace.OSpace));

                var ocMappingCollection = (DefaultObjectMappingItemCollection)workspace.GetItemCollection(DataSpace.OCSpace);
                Assert.Same(objectItemCollection, ocMappingCollection.ObjectItemCollection);
                Assert.Same(edmItemCollection, ocMappingCollection.EdmItemCollection);
            }
            public void GetItemCollection_on_both_C_and_S_space_using_item_collections_with_inconsistent_versions_throws_MetadataException()
            {
                var edmItemCollection = new EdmItemCollection(new[] { XDocument.Parse(_csdlV3).CreateReader() });
                var storeItemCollection =
                    new StoreItemCollection(
                        new[]
                            {
                                XDocument.Parse(string.Format(CultureInfo.InvariantCulture, SsdlTemplate, XmlConstants.TargetNamespace_2))
                                    .CreateReader()
                            });

                var workspace = new MetadataWorkspace(
                    () => edmItemCollection,
                    () => storeItemCollection,
                    () => null);

                workspace.GetItemCollection(DataSpace.CSpace); // this sets up the MetadataWorkspace's expected schema version as the csdl version i.e. 3.0
                Assert.Equal(
                    Resources.Strings.DifferentSchemaVersionInCollection("StoreItemCollection", 2.0, 3.0),
                    Assert.Throws<MetadataException>(() => workspace.GetItemCollection(DataSpace.SSpace)).Message);
            }
            public void Registering_o_space_does_not_cause_oc_mapping_to_be_registered_if_c_space_is_not_registered()
            {
                var objectItemCollection = new ObjectItemCollection();

                var workspace = new MetadataWorkspace();
#pragma warning disable 612,618
                workspace.RegisterItemCollection(objectItemCollection);
#pragma warning restore 612,618

                Assert.Same(objectItemCollection, workspace.GetItemCollection(DataSpace.OSpace));
                ItemCollection _;
                Assert.False(workspace.TryGetItemCollection(DataSpace.OCSpace, out _));
            }
Exemplo n.º 58
0
        /// <summary>
        /// This constructor allows to skip the initialization code for testing purposes.
        /// </summary>
        internal EntityConnection(MetadataWorkspace workspace, DbConnection connection, bool skipInitialization)
        {
            if (!skipInitialization)
            {
                if (!workspace.IsItemCollectionAlreadyRegistered(DataSpace.CSpace))
                {
                    throw new ArgumentException(Strings.EntityClient_ItemCollectionsNotRegisteredInWorkspace("EdmItemCollection"));
                }
                if (!workspace.IsItemCollectionAlreadyRegistered(DataSpace.SSpace))
                {
                    throw new ArgumentException(Strings.EntityClient_ItemCollectionsNotRegisteredInWorkspace("StoreItemCollection"));
                }
                if (!workspace.IsItemCollectionAlreadyRegistered(DataSpace.CSSpace))
                {
                    throw new ArgumentException(
                        Strings.EntityClient_ItemCollectionsNotRegisteredInWorkspace("StorageMappingItemCollection"));
                }

                if (connection.State
                    != ConnectionState.Closed)
                {
                    throw new ArgumentException(Strings.EntityClient_ConnectionMustBeClosed);
                }

                // Verify that a factory can be retrieved
                if (DbProviderFactories.GetFactory(connection) == null)
                {
                    throw new ProviderIncompatibleException(Strings.EntityClient_DbConnectionHasNoProvider(connection));
                }

                var collection = (StoreItemCollection)workspace.GetItemCollection(DataSpace.SSpace);

                _providerFactory = collection.StoreProviderFactory;
                _userOwnsStoreConnection = true;
                _initialized = true;
            }

            _metadataWorkspace = workspace;
            _storeConnection = connection;
        }