Ejemplo n.º 1
0
        private MetadataWorkspace GetMetadataWorkspace()
        {
            MetadataWorkspace metadataWorkspace = System.Data.Mapping.MetadataWorkspaceUtilities.CreateMetadataWorkspace(this.ContextType);

            metadataWorkspace.LoadFromAssembly(this.ContextType.Assembly);
            return(metadataWorkspace);
        }
        // <summary>
        // Performs o-space loading for the type and returns false if the type is not in the model.
        // </summary>
        internal bool TryUpdateEntitySetMappingsForType(Type entityType)
        {
            Debug.Assert(
                entityType == ObjectContextTypeCache.GetObjectType(entityType), "Proxy type should have been converted to real type");

            if (_entitySetMappingsCache.ContainsKey(entityType))
            {
                return(true);
            }

            // We didn't find the type on first look, but this could be because the o-space loading
            // has not happened.  So we try that, update our cached mappings, and try again.
            var typeToLoad = entityType;

            do
            {
                _workspace.LoadFromAssembly(typeToLoad.Assembly());
                typeToLoad = typeToLoad.BaseType();
            }while (typeToLoad != null &&
                    typeToLoad != typeof(Object));

            lock (_entitySetMappingsUpdateLock)
            {
                if (_entitySetMappingsCache.ContainsKey(entityType))
                {
                    return(true);
                }
                UpdateEntitySetMappings();
            }

            return(_entitySetMappingsCache.ContainsKey(entityType));
        }
Ejemplo n.º 3
0
        public static StructuralType GetEdmType(MetadataWorkspace workspace, Type clrType)
        {
            if (workspace == null)
            {
                throw new ArgumentNullException("workspace");
            }
            if (clrType == null)
            {
                throw new ArgumentNullException("clrType");
            }
            if (clrType.IsPrimitive || clrType == typeof(object))
            {
                return(null);
            }
            EdmType edmType = null;

            do
            {
                if (!workspace.TryGetType(clrType.Name, clrType.Namespace, DataSpace.OSpace, out edmType))
                {
                    workspace.LoadFromAssembly(clrType.Assembly);
                    workspace.TryGetType(clrType.Name, clrType.Namespace, DataSpace.OSpace, out edmType);
                }
            }while (edmType == null && (clrType = clrType.BaseType) != typeof(object) && clrType != null);
            StructuralType result = null;

            if (edmType != null && (edmType.BuiltInTypeKind == BuiltInTypeKind.EntityType || edmType.BuiltInTypeKind == BuiltInTypeKind.ComplexType))
            {
                workspace.TryGetEdmSpaceType((StructuralType)edmType, out result);
            }
            return(result);
        }
Ejemplo n.º 4
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);
        }
        partial void OnContextCreated()
        {
            try
            {
                MetadataWorkspace.LoadFromAssembly(Assembly.GetAssembly(typeof(BsoArchiveEntities)));
            }
            catch (Exception ex) { }

            SavingChanges += new EventHandler(Entities_SavingChanges);
        }
 public static void InitializeMetadataWorkspace(TestContext testContext)
 {
     StringReader sr = new StringReader(testCsdl);
     XmlReader reader = XmlReader.Create(sr);
     metadataWorkspace = new MetadataWorkspace();
     EdmItemCollection edmItemCollection = new EdmItemCollection(new XmlReader[] { reader });
     metadataWorkspace.RegisterItemCollection(edmItemCollection);
     metadataWorkspace.RegisterItemCollection(new ObjectItemCollection());
     metadataWorkspace.LoadFromAssembly(Assembly.GetExecutingAssembly());            
 }
Ejemplo n.º 7
0
        public static void InitializeMetadataWorkspace(TestContext testContext)
        {
            StringReader sr     = new StringReader(testCsdl);
            XmlReader    reader = XmlReader.Create(sr);

            metadataWorkspace = new MetadataWorkspace();
            EdmItemCollection edmItemCollection = new EdmItemCollection(new XmlReader[] { reader });

            metadataWorkspace.RegisterItemCollection(edmItemCollection);
            metadataWorkspace.RegisterItemCollection(new ObjectItemCollection());
            metadataWorkspace.LoadFromAssembly(Assembly.GetExecutingAssembly());
        }
Ejemplo n.º 8
0
        private static StructuralType GetEdmType(MetadataWorkspace workspace)
        {
            StructuralType objectSpaceType;

            workspace.LoadFromAssembly(typeof(T).Assembly);
            if (!workspace.TryGetItem <StructuralType>(typeof(T).FullName, DataSpace.OSpace, out objectSpaceType))
            {
                //throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Messages.UnableToFindMetadataForType, typeof(T)));
            }
            StructuralType edmSpaceType = workspace.GetEdmSpaceType(objectSpaceType);

            return(edmSpaceType);
        }
            public void LoadFromAssembly_checks_only_given_assembly_for_views()
            {
                var mockCache = new Mock <IViewAssemblyCache>();
                var workspace = new MetadataWorkspace(
                    () => new EdmItemCollection(Enumerable.Empty <XmlReader>()),
                    () => null,
                    () => null,
                    () => new ObjectItemCollection(mockCache.Object));

                workspace.LoadFromAssembly(typeof(object).Assembly);

                mockCache.Verify(m => m.CheckAssembly(typeof(object).Assembly, false), Times.Once());
            }
Ejemplo n.º 10
0
        /// <summary>
        /// Retrieves the <see cref="System.Data.Entity.Core.Metadata.Edm.StructuralType"/> corresponding to the given CLR type (where the
        /// type is an entity or complex type).
        /// </summary>
        /// <remarks>
        /// If no mapping exists for <paramref name="clrType"/>, but one does exist for one of its base
        /// types, we will return the mapping for the base type.
        /// </remarks>
        /// <param name="workspace">The <see cref="System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace"/></param>
        /// <param name="clrType">The CLR type</param>
        /// <returns>The <see cref="System.Data.Entity.Core.Metadata.Edm.StructuralType"/> corresponding to that CLR type, or <c>null</c> if the Type
        /// is not mapped.</returns>
        public static StructuralType GetEdmType(MetadataWorkspace workspace, Type clrType)
        {
            if (workspace == null)
            {
                throw Error.ArgumentNull("workspace");
            }
            if (clrType == null)
            {
                throw Error.ArgumentNull("clrType");
            }

            if (clrType.IsPrimitive || clrType == typeof(object))
            {
                // want to avoid loading searching system assemblies for
                // types we know aren't entity or complex types
                return(null);
            }

            // We first locate the EdmType in "OSpace", which matches the name and namespace of the CLR type
            EdmType edmType;

            do
            {
                if (workspace.TryGetType(clrType.Name, clrType.Namespace, DataSpace.OSpace, out edmType))
                {
                    continue;
                }
                // If EF could not find this type, it could be because it is not loaded into
                // its current workspace.  In this case, we explicitly load the assembly containing
                // the CLR type and try again.
                workspace.LoadFromAssembly(clrType.Assembly);
                workspace.TryGetType(clrType.Name, clrType.Namespace, DataSpace.OSpace, out edmType);
            } while (edmType == null && (clrType = clrType.BaseType) != typeof(object) && clrType != null);

            // Next we locate the StructuralType from the EdmType.
            // This 2-step process is necessary when the types CLR namespace does not match Edm namespace.
            // Look at the EdmEntityTypeAttribute on the generated entity classes to see this Edm namespace.
            StructuralType structuralType = null;

            if (edmType != null &&
                (edmType.BuiltInTypeKind == BuiltInTypeKind.EntityType || edmType.BuiltInTypeKind == BuiltInTypeKind.ComplexType))
            {
                workspace.TryGetEdmSpaceType((StructuralType)edmType, out structuralType);
            }

            return(structuralType);
        }
        /// <summary>
        /// Retrieves the <see cref="StructuralType"/> corresponding to the given CLR type (where the
        /// type is an entity or complex type).
        /// </summary>
        /// <remarks>
        /// If no mapping exists for <paramref name="clrType"/>, but one does exist for one of its base 
        /// types, we will return the mapping for the base type.
        /// </remarks>
        /// <param name="workspace">The <see cref="MetadataWorkspace"/></param>
        /// <param name="clrType">The CLR type</param>
        /// <returns>The <see cref="StructuralType"/> corresponding to that CLR type, or <c>null</c> if the Type
        /// is not mapped.</returns>
        public static StructuralType GetEdmType(MetadataWorkspace workspace, Type clrType)
        {
            if (workspace == null)
            {
                throw new ArgumentNullException("workspace");
            }
            if (clrType == null)
            {
                throw new ArgumentNullException("clrType");
            }

            if (clrType.IsPrimitive || clrType == typeof(object))
            {
                // want to avoid loading searching system assemblies for
                // types we know aren't entity or complex types
                return null;
            }

            // We first locate the EdmType in "OSpace", which matches the name and namespace of the CLR type
            EdmType edmType = null;
            do
            {
                if (!workspace.TryGetType(clrType.Name, clrType.Namespace, DataSpace.OSpace, out edmType))
                {
                    // If EF could not find this type, it could be because it is not loaded into
                    // its current workspace.  In this case, we explicitly load the assembly containing 
                    // the CLR type and try again.
                    workspace.LoadFromAssembly(clrType.Assembly);
                    workspace.TryGetType(clrType.Name, clrType.Namespace, DataSpace.OSpace, out edmType);
                }
            }
            while (edmType == null && (clrType = clrType.BaseType) != typeof(object) && clrType != null);

            // Next we locate the StructuralType from the EdmType.
            // This 2-step process is necessary when the types CLR namespace does not match Edm namespace.
            // Look at the EdmEntityTypeAttribute on the generated entity classes to see this Edm namespace.
            StructuralType structuralType = null;
            if (edmType != null &&
                (edmType.BuiltInTypeKind == BuiltInTypeKind.EntityType || edmType.BuiltInTypeKind == BuiltInTypeKind.ComplexType))
            {
                workspace.TryGetEdmSpaceType((StructuralType)edmType, out structuralType);
            }

            return structuralType;
        }
Ejemplo n.º 12
0
        public static Metadata Generate(Assembly modelAssembly, string modelName)
        {
            var conceptualResource = modelAssembly.GetManifestResourceStream(modelName + ".csdl");

            Debug.Assert(conceptualResource != null, "conceptualResource != null");
            var conceptualReader     = XmlReader.Create(conceptualResource);
            var itemCollection       = new EdmItemCollection(new[] { conceptualReader });
            var objectItemCollection = new ObjectItemCollection();
            var metadataWorkspace    = new MetadataWorkspace(
                () => itemCollection,
                () => null,
                () => null,
                () => objectItemCollection
                );

            metadataWorkspace.LoadFromAssembly(modelAssembly);
            return(Generate(metadataWorkspace, itemCollection, objectItemCollection, modelAssembly, modelName));
        }
        public static EntityType GetCSpacetype(Type currentType, MetadataWorkspace mdw)
        {
            mdw.LoadFromAssembly(currentType.Assembly);

            EntityType     ospaceEntityType = null;
            StructuralType cspaceEntityType = null;

            if (mdw.TryGetItem <EntityType>(
                    currentType.FullName, DataSpace.OSpace, out ospaceEntityType))
            {
                if (mdw.TryGetEdmSpaceType(ospaceEntityType,
                                           out cspaceEntityType))
                {
                    return(cspaceEntityType as EntityType);
                }
            }

            return(null);
        }
Ejemplo n.º 14
0
        private static XDocument UpdateCSpaceOSpaceMapping(XDocument xDoc, Assembly assembly, String resourcePrefix)
        {
            String[] res;
            if (resourcePrefix == "")
            {
                res = new string[] { "res://*/" };
            }
            else
            {
                var pre = "res://*/" + resourcePrefix;
                res = new String[] { pre + ".csdl", pre + ".msl", pre + ".ssdl" };
            }
            var metadataWs = new MetadataWorkspace(
                res,
                new Assembly[] { assembly });

            // force an OSpace load - UGH - this was hard to find.... need to create the object item collection before loading assembly
            metadataWs.RegisterItemCollection(new ObjectItemCollection());
            metadataWs.LoadFromAssembly(assembly);

            return(UpdateCSpaceOSpaceMappingCore(xDoc, metadataWs));
        }
            public void LoadFromAssembly_checks_only_given_assembly_for_views()
            {
                var mockCache = new Mock<IViewAssemblyCache>();
                var workspace = new MetadataWorkspace(
                    () => new EdmItemCollection(Enumerable.Empty<XmlReader>()),
                    () => null,
                    () => null,
                    () => new ObjectItemCollection(mockCache.Object));

                workspace.LoadFromAssembly(typeof(object).Assembly);

                mockCache.Verify(m => m.CheckAssembly(typeof(object).Assembly, false), Times.Once());
            }
        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"));
        }
Ejemplo n.º 17
0
 private static void LoadAssemblyIntoWorkspace(MetadataWorkspace workspace, Assembly assembly)
 {
     workspace.LoadFromAssembly(assembly);
 }
        public static EntityType GetCSpacetype(Type currentType, MetadataWorkspace mdw)
        {
            mdw.LoadFromAssembly(currentType.Assembly);

            EntityType ospaceEntityType = null;
            StructuralType cspaceEntityType = null;
            if (mdw.TryGetItem<EntityType>(
                currentType.FullName, DataSpace.OSpace, out ospaceEntityType))
            {
                if (mdw.TryGetEdmSpaceType(ospaceEntityType,
                    out cspaceEntityType))
                    return cspaceEntityType as EntityType;
            }

            return null;
        }
        private bool SetEntityConnection(List<string> metadataPaths, EntityConnectionStringBuilder connStrBuilder)
        {
            // It's possible the metadata was specified in the original connection string, but we filtered out everything due to not being able to resolve it to anything.
            // In that case, warnings have already been displayed to indicate which paths were removed, so no need to display another message.            
            if (metadataPaths.Count > 0)
            {
                try
                {
                    // Get the connection first, because it might be needed to gather provider services information
                    DbConnection dbConnection = GetDbConnection(connStrBuilder);

                    MetadataWorkspace metadataWorkspace = new MetadataWorkspace(metadataPaths, _assemblies);

                    // Ensure that we have all of the item collections registered. If some of them are missing this will cause problems eventually if we need to 
                    // execute a query to get detailed schema information, but that will be handled later. For now just register everything to prevent errors in the 
                    // stack that would not be understood by the user in the designer at this point.
                    ItemCollection edmItemCollection;
                    ItemCollection storeItemCollection;
                    ItemCollection csItemCollection;
                    if (!metadataWorkspace.TryGetItemCollection(DataSpace.CSpace, out edmItemCollection))
                    {
                        edmItemCollection = new EdmItemCollection();
                        metadataWorkspace.RegisterItemCollection(edmItemCollection);
                    }

                    if (!metadataWorkspace.TryGetItemCollection(DataSpace.SSpace, out storeItemCollection))
                    {
                        return false;
                    }

                    if (!metadataWorkspace.TryGetItemCollection(DataSpace.CSSpace, out csItemCollection))
                    {
                        Debug.Assert(edmItemCollection != null && storeItemCollection != null, "edm and store ItemCollection should be populated already");
                        metadataWorkspace.RegisterItemCollection(new StorageMappingItemCollection(edmItemCollection as EdmItemCollection, storeItemCollection as StoreItemCollection));
                    }
                    
                    // Create an ObjectItemCollection beforehand so that we can load objects by-convention
                    metadataWorkspace.RegisterItemCollection(new ObjectItemCollection());

                    // Load OSpace metadata from all of the assemblies we know about
                    foreach (Assembly assembly in _assemblies)
                    {
                        metadataWorkspace.LoadFromAssembly(assembly);
                    }
                    
                    if (dbConnection != null)
                    {
                        _entityConnection = new EntityConnection(metadataWorkspace, dbConnection);
                        return true;
                    }
                    // else the DbConnection could not be created and the error should have already been displayed
                }
                catch (Exception ex)
                {   
                    StringBuilder exceptionMessage = new StringBuilder();
                    exceptionMessage.AppendLine(Strings.Error_MetadataLoadError);
                    exceptionMessage.AppendLine();
                    exceptionMessage.Append(ex.Message);
                    ShowError(exceptionMessage.ToString());
                }
            }

            return false;
        }
Ejemplo n.º 20
0
 private static void LoadAssemblyIntoWorkspace(MetadataWorkspace workspace, Assembly assembly)
 {
     workspace.LoadFromAssembly(assembly);
 }