public void Prepare_returns_a_new_instance()
        {
            var objectQueryExecutionPlanFactory = new ObjectQueryExecutionPlanFactory(
                Common.Internal.Materialization.MockHelper.CreateTranslator<object>());

            var metadataWorkspace = new MetadataWorkspace();
            var edmItemCollection = new EdmItemCollection();
            metadataWorkspace.RegisterItemCollection(edmItemCollection);
            metadataWorkspace.RegisterItemCollection(new ObjectItemCollection());
            var fakeSqlProviderManifest = new FakeSqlProviderServices().GetProviderManifest("2008");
            var storeItemCollection = new StoreItemCollection(FakeSqlProviderFactory.Instance, fakeSqlProviderManifest, "2008");
            metadataWorkspace.RegisterItemCollection(storeItemCollection);
            metadataWorkspace.RegisterItemCollection(new StorageMappingItemCollection(edmItemCollection, storeItemCollection, Enumerable.Empty<XmlReader>()));

            var fakeSqlConnection = new FakeSqlConnection();
            fakeSqlConnection.ConnectionString = "foo";
            var entityConnection = new EntityConnection(metadataWorkspace, fakeSqlConnection, false);

            var objectContext = new ObjectContext(entityConnection);
            var dbExpression = new DbNullExpression(TypeUsage.Create(fakeSqlProviderManifest.GetStoreTypes().First()));
            var dbQueryCommandTree = new DbQueryCommandTree(metadataWorkspace, DataSpace.CSpace,
               dbExpression, validate: false);
            var parameters = new List<Tuple<ObjectParameter, QueryParameterExpression>>();

            var objectQueryExecutionPlan = objectQueryExecutionPlanFactory.Prepare(objectContext, dbQueryCommandTree, typeof(object),
                MergeOption.NoTracking, new Span(), parameters, aliasGenerator: null);

            Assert.NotNull(objectQueryExecutionPlan);
        }
        /// <summary>
        ///     API for checkin whether database exists or not.
        ///     This will internally only check whether the file that the connection points to exists or not.
        ///     Note: In case of SQLCE, timeout and storeItemCollection parameters are ignored.
        /// </summary>
        /// <param name="connection"> Connection </param>
        /// <param name="timeOut"> Timeout for internal commands. </param>
        /// <param name="storeItemCollection"> Item Collection. </param>
        /// <returns> Bool indicating whether database exists or not. </returns>
        protected override bool DbDatabaseExists(DbConnection connection, int? timeOut, StoreItemCollection storeItemCollection)
        {
            Check.NotNull(connection, "connection");
            Check.NotNull(storeItemCollection, "storeItemCollection");

            // Validate and cast the connection.
            ValidateConnection(connection);

            if (_isLocalProvider)
            {
                return CommonUtils.DatabaseExists(connection.DataSource);
            }
            else
            {
                Type rdpType;

                // If we are working with RDP, then we will need to invoke the APIs through reflection.
                var engine = RemoteProviderHelper.GetRemoteSqlCeEngine(connection.ConnectionString, out rdpType);
                Debug.Assert(engine != null);

                var mi = rdpType.GetMethod("FileExists", new[] { typeof(string), typeof(int?) });
                Debug.Assert(mi != null);

                // We will pass 'timeout' to RDP, this will be used as timeout period for connecting and executing on TDSServer.
                return (bool)(mi.Invoke(engine, new object[] { connection.DataSource, timeOut }));
            }
        }
        /// <summary>
        ///     Helper function for generating the scripts for tables & constraints.
        /// </summary>
        /// <param name="itemCollection"> </param>
        /// <returns> </returns>
        internal static List<string> CreateObjectsScript(StoreItemCollection itemCollection, bool returnWarnings)
        {
            var builder = new SqlDdlBuilder();

            // Iterate over the container.
            foreach (var container in itemCollection.GetItems<EntityContainer>())
            {
                // Generate create table statements.
                foreach (var set in container.BaseEntitySets)
                {
                    // If it is a type of entitySet, generate Create Table statements.
                    var entitySet = set as EntitySet;
                    if (entitySet != null)
                    {
                        builder.AppendCreateTable(entitySet);
                    }
                }

                // Generate Foreign Key constraints.
                foreach (var set in container.BaseEntitySets)
                {
                    // If it is association set, generate Foreign Key constraints.
                    var associationSet = set as AssociationSet;
                    if (associationSet != null)
                    {
                        builder.AppendCreateForeignKeys(associationSet);
                    }
                }
            }

            // Return the final command text.
            return builder.GetCommandText(returnWarnings);
        }
Ejemplo n.º 4
0
        public void Pregenerated_views_are_found_for_EDMX_model()
        {
            var edmItemCollection = new EdmItemCollection(new[] { XDocument.Parse(PregenContextEdmx.Csdl).CreateReader() });
            var storeItemCollection = new StoreItemCollection(new[] { XDocument.Parse(PregenContextEdmx.Ssdl).CreateReader() });

            IList<EdmSchemaError> errors;
            var storageMappingItemCollection = StorageMappingItemCollection.Create(
                edmItemCollection,
                storeItemCollection,
                new[] { XDocument.Parse(PregenContextEdmx.Msl).CreateReader() },
                null,
                out errors);

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

            using (var context = new PregenContextEdmx(workspace))
            {
                var _ = context.Blogs.ToString(); // Trigger view loading

                Assert.True(PregenContextEdmxViews.View0Accessed);
                Assert.True(PregenContextEdmxViews.View1Accessed);
            }
        }
        public static StorageMappingItemCollection GetStorageMappingItemCollection(
            this XDocument model, out DbProviderInfo providerInfo)
        {
            DebugCheck.NotNull(model);

            var edmItemCollection
                = new EdmItemCollection(
                    new[]
                        {
                            model.Descendants(EdmXNames.Csdl.SchemaNames).Single().CreateReader()
                        });

            var ssdlSchemaElement = model.Descendants(EdmXNames.Ssdl.SchemaNames).Single();

            providerInfo = new DbProviderInfo(
                ssdlSchemaElement.ProviderAttribute(),
                ssdlSchemaElement.ProviderManifestTokenAttribute());

            var storeItemCollection
                = new StoreItemCollection(
                    new[]
                        {
                            ssdlSchemaElement.CreateReader()
                        });

            return new StorageMappingItemCollection(
                edmItemCollection,
                storeItemCollection,
                new[] { new XElement(model.Descendants(EdmXNames.Msl.MappingNames).Single()).CreateReader() });
        }
        /// <summary>
        /// Creates the MetadataWorkspace for the given context type and base context type.
        /// </summary>
        /// <param name="contextType">The type of the context.</param>
        /// <param name="baseContextType">The base context type (DbContext or ObjectContext).</param>
        /// <returns>The generated <see cref="System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace"/></returns>
        public static MetadataWorkspace CreateMetadataWorkspaceFromResources(Type contextType, Type baseContextType)
        {
            // get the set of embedded mapping resources for the target assembly and create
            // a metadata workspace info for each group
            var metadataResourcePaths = FindMetadataResources(contextType.Assembly);
            var workspaceInfos = GetMetadataWorkspaceInfos(metadataResourcePaths);

            // Search for the correct EntityContainer by name and if found, create
            // a comlete MetadataWorkspace and return it
            foreach (var workspaceInfo in workspaceInfos) {
                var edmItemCollection = new EdmItemCollection(workspaceInfo.Csdl);

                var currentType = contextType;
                while (currentType != baseContextType && currentType != typeof (object)) {
                    EntityContainer container;
                    if (edmItemCollection.TryGetEntityContainer(currentType.Name, out container)) {
                        var store = new StoreItemCollection(workspaceInfo.Ssdl);
                        var mapping = new StorageMappingItemCollection(edmItemCollection, store, workspaceInfo.Msl);
                        var workspace = new MetadataWorkspace();
                        workspace.RegisterItemCollection(edmItemCollection);
                        workspace.RegisterItemCollection(store);
                        workspace.RegisterItemCollection(mapping);
                        workspace.RegisterItemCollection(new ObjectItemCollection());
                        return workspace;
                    }

                    currentType = currentType.BaseType;
                }
            }
            return null;
        }
        /// <summary>
        ///     API for generating script for creating schema objects from the Store Item Collection.
        /// </summary>
        /// <param name="providerManifestToken"> Provider manifest </param>
        /// <param name="storeItemCollection"> Store items </param>
        /// <returns> T-SQL script for generating schema objects. </returns>
        protected override string DbCreateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection)
        {
            Check.NotNull(providerManifestToken, "providerManifestToken");
            Check.NotNull(storeItemCollection, "storeItemCollection");

            // Call the helper for creating schema objects.
            return string.Concat(SqlDdlBuilder.CreateObjectsScript(storeItemCollection, true).ToArray());
        }
Ejemplo n.º 8
0
		//protected override string DbCreateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection)
		//{
		//    throw new NotImplementedException();
		//}

		protected override bool DbDatabaseExists(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection)
		{
			if (connection.Database == ":memory:")
			{
				return false;
			}
			return false;
		}
Ejemplo n.º 9
0
		protected override void DbCreateDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection)
		{
		    var sql = DdlBuilder.CreateObjectsScript(storeItemCollection);
		    connection.Open();
		    using (var cmd = connection.CreateCommand())
		    {
		        cmd.CommandText = sql;
		        cmd.ExecuteNonQuery();
		    }
		}
Ejemplo n.º 10
0
        public static string GenerateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection)
        {
            if (storeItemCollection == null)
                return string.Empty;

            var result = new StringBuilder();
            result.Append(string.Join(Environment.NewLine, GenerateTables(storeItemCollection)));
            result.AppendLine();
            result.Append(string.Join(Environment.NewLine, GenerateForeignKeys(storeItemCollection)));
            result.AppendLine();
            return result.ToString();
        }
Ejemplo n.º 11
0
        /// <summary>
        ///     API for deleting the database.
        ///     In SQLCE case, this will translate to File.Delete() call.
        ///     Note: Timeout and storeItemCollection parameters are ignored.
        /// </summary>
        /// <param name="connection"> </param>
        /// <param name="timeOut"> </param>
        /// <param name="storeItemCollection"> </param>
        protected override void DbDeleteDatabase(DbConnection connection, int? timeOut, StoreItemCollection storeItemCollection)
        {
            // Validate that connection is a SqlCeConnection.
            ValidateConnection(connection);

            // We don't support create/delete database operations inside a transaction as they can't be rolled back.
            if (InTransactionScope())
            {
                throw ADP1.DeleteDatabaseNotAllowedWithinTransaction();
            }

            // Throw an exception if connection is open.
            // We should not close the connection because user could have result sets/data readers associated with this connection.
            // Thus, it is users responsiblity to close the connection before calling delete database.
            //
            if (connection.State
                == ConnectionState.Open)
            {
                throw ADP1.DeleteDatabaseWithOpenConnection();
            }

            if (_isLocalProvider)
            {
                CommonUtils.DeleteDatabase(connection.DataSource);
            }
            else
            {
                try
                {
                    Type rdpType;

                    // If we are working with RDP, then we will need to invoke the APIs through reflection.
                    var engine = RemoteProviderHelper.GetRemoteSqlCeEngine(connection.ConnectionString, out rdpType);
                    Debug.Assert(engine != null);

                    // Invoke the required method on SqlCeEngine.
                    var mi = rdpType.GetMethod("DeleteDatabaseWithError", new[] { typeof(string), typeof(int?) });
                    Debug.Assert(mi != null);

                    // We will pass 'timeout' to RDP, this will be used as timeout period for connecting and executing on TDSServer.
                    mi.Invoke(engine, new object[] { connection.DataSource, timeOut });
                }
                catch (Exception e)
                {
                    throw e.GetBaseException();
                }
            }
        }
        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;
        }
Ejemplo n.º 13
0
 static IEnumerable<string> GenerateForeignKeys(StoreItemCollection storeItems)
 {
     foreach (var associationSet in storeItems.GetItems<EntityContainer>()[0].BaseEntitySets.OfType<AssociationSet>())
     {
         var result = new StringBuilder();
         ReferentialConstraint constraint = associationSet.ElementType.ReferentialConstraints.Single<ReferentialConstraint>();
         AssociationSetEnd end = associationSet.AssociationSetEnds[constraint.FromRole.Name];
         AssociationSetEnd end2 = associationSet.AssociationSetEnds[constraint.ToRole.Name];
         result.AppendFormat("ALTER TABLE {0}.{1} ADD FOREIGN KEY ({2}) REFERENCES {3}.{4}({5}){6};",
             SqlGenerator.QuoteIdentifier(MetadataHelpers.GetSchemaName(end2.EntitySet)), 
             SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(end2.EntitySet)),
             string.Join(", ", constraint.ToProperties.Select(fk => SqlGenerator.QuoteIdentifier(fk.Name))),
             SqlGenerator.QuoteIdentifier(MetadataHelpers.GetSchemaName(end.EntitySet)),
             SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(end.EntitySet)),
             string.Join(", ", constraint.FromProperties.Select(pk => SqlGenerator.QuoteIdentifier(pk.Name))),
             end.CorrespondingAssociationEndMember.DeleteBehavior == OperationAction.Cascade ? " ON DELETE CASCADE" : string.Empty);
         yield return result.ToString();
     }
 }
Ejemplo n.º 14
0
 static IEnumerable<string> GenerateTables(StoreItemCollection storeItems)
 {
     foreach (var entitySet in storeItems.GetItems<EntityContainer>()[0].BaseEntitySets.OfType<EntitySet>())
     {
         var result = new StringBuilder();
         var tableName = MetadataHelpers.GetTableName(entitySet);
         var schemaName = MetadataHelpers.GetSchemaName(entitySet);
         result.AppendFormat("CREATE TABLE {0}.{1} (", SqlGenerator.QuoteIdentifier(schemaName), SqlGenerator.QuoteIdentifier(tableName));
         result.AppendLine();
         result.Append("\t");
         result.Append(string.Join("," + Environment.NewLine + "\t", MetadataHelpers.GetProperties(entitySet.ElementType).Select(p => GenerateColumn(p))));
         result.Append(");");
         result.AppendLine();
         result.AppendFormat("ALTER TABLE {0}.{1} ADD PRIMARY KEY ({2});",
             SqlGenerator.QuoteIdentifier(schemaName),
             SqlGenerator.QuoteIdentifier(tableName),
             string.Join(", ", entitySet.ElementType.KeyMembers.Select(pk => SqlGenerator.QuoteIdentifier(pk.Name))));
         result.AppendLine();
         yield return result.ToString();
     }
 }
Ejemplo n.º 15
0
        public static string DropObjects(StoreItemCollection itemCollection)
        {
            var builder = new SqlScripts();

            foreach (var container in itemCollection.GetItems<EntityContainer>())
            {
                var entitySets = container.BaseEntitySets.OfType<EntitySet>().OrderBy(s => s.Name);

                foreach (var associationSet in container.BaseEntitySets.OfType<AssociationSet>().OrderBy(s => s.Name))
                {
                    builder.AppendDropForeignKeys(associationSet);
                }

                foreach (var entitySet in container.BaseEntitySets.OfType<EntitySet>().OrderBy(s => s.Name))
                {
                    builder.AppendDropTable(entitySet);
                }
            }

            return builder.GetCommandText();
        }
            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);
            }
        public static StorageMappingItemCollection ToStorageMappingItemCollection(
            this DbDatabaseMapping databaseMapping, EdmItemCollection itemCollection,
            StoreItemCollection storeItemCollection)
        {
            DebugCheck.NotNull(databaseMapping);
            DebugCheck.NotNull(itemCollection);
            DebugCheck.NotNull(storeItemCollection);

            var stringBuilder = new StringBuilder();

            using (var xmlWriter = XmlWriter.Create(
                stringBuilder, new XmlWriterSettings
                    {
                        Indent = true
                    }))
            {
                new MslSerializer().Serialize(databaseMapping, xmlWriter);
            }

            using (var xmlReader = XmlReader.Create(new StringReader(stringBuilder.ToString())))
            {
                return new StorageMappingItemCollection(itemCollection, storeItemCollection, new[] { xmlReader });
            }
        }
        private static StorageMappingItemCollection ToStorageMappingItemCollection(
            this DbDatabaseMapping databaseMapping, EdmItemCollection itemCollection,
            StoreItemCollection storeItemCollection)
        {
            Contract.Requires(databaseMapping != null);
            Contract.Requires(itemCollection != null);
            Contract.Requires(storeItemCollection != null);

            var stringBuilder = new StringBuilder();

            using (var xmlWriter = XmlWriter.Create(
                stringBuilder, new XmlWriterSettings
                    {
                        Indent = true
                    }))
            {
                new MslSerializer().Serialize(databaseMapping, xmlWriter);
            }

            using (var xmlReader = XmlReader.Create(new StringReader(stringBuilder.ToString())))
            {
                return new StorageMappingItemCollection(itemCollection, storeItemCollection, new[] { xmlReader });
            }
        }
 protected override string DbCreateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection)
 {
     return ScriptBuilder.GenerateDatabaseScript(providerManifestToken, storeItemCollection);
 }
Ejemplo n.º 20
0
		protected override void DbDeleteDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection)
		{
			base.DbDeleteDatabase(connection, commandTimeout, storeItemCollection);
		}
Ejemplo n.º 21
0
		protected override string DbCreateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection)
		{
			return DdlBuilder.CreateObjectsScript(storeItemCollection);
		}
Ejemplo n.º 22
0
        private static Mock<MetadataWorkspace> CreateMetadataWorkspaceMock()
        {
            var storeItemCollection = new StoreItemCollection(
                GenericProviderFactory<DbProviderFactory>.Instance, new SqlProviderManifest("2008"), "System.Data.FakeSqlClient", "2008");

            var metadataWorkspaceMock = new Mock<MetadataWorkspace>(MockBehavior.Strict);
            metadataWorkspaceMock.Setup(m => m.GetItemCollection(DataSpace.SSpace)).Returns(storeItemCollection);
            metadataWorkspaceMock.Setup(m => m.IsItemCollectionAlreadyRegistered(DataSpace.SSpace)).Returns(true);
            metadataWorkspaceMock.Setup(m => m.IsItemCollectionAlreadyRegistered(DataSpace.CSpace)).Returns(true);
            metadataWorkspaceMock.Setup(m => m.IsItemCollectionAlreadyRegistered(DataSpace.CSSpace)).Returns(true);

            return metadataWorkspaceMock;
        }
 internal StorageMappingItemCollection(
     EdmItemCollection edmCollection,
     StoreItemCollection storeCollection,
     IEnumerable<XmlReader> xmlReaders,
     IList<string> filePaths)
     : base(DataSpace.CSSpace)
 {
     Init(edmCollection, storeCollection, xmlReaders, filePaths, true /*throwOnError*/);
 }
        // <summary>
        // constructor that takes in a list of XmlReaders and creates metadata for mapping
        // in all the files.
        // </summary>
        // <param name="edmItemCollection"> The edm metadata collection that this mapping is to use </param>
        // <param name="storeItemCollection"> The store metadata collection that this mapping is to use </param>
        // <param name="xmlReaders"> The XmlReaders to load mapping from </param>
        // <param name="filePaths"> Mapping URIs </param>
        // <param name="errors"> a list of errors for each file loaded </param>
        private StorageMappingItemCollection(
            EdmItemCollection edmItemCollection,
            StoreItemCollection storeItemCollection,
            IEnumerable<XmlReader> xmlReaders,
            IList<string> filePaths,
            out IList<EdmSchemaError> errors)
            : base(DataSpace.CSSpace)
        {
            DebugCheck.NotNull(edmItemCollection);
            DebugCheck.NotNull(storeItemCollection);
            DebugCheck.NotNull(xmlReaders);

            errors = Init(edmItemCollection, storeItemCollection, xmlReaders, filePaths, false /*throwOnError*/);
        }
        public StorageMappingItemCollection(
            EdmItemCollection edmCollection,
            StoreItemCollection storeCollection,
            IEnumerable<XmlReader> xmlReaders)
            : base(DataSpace.CSSpace)
        {
            Check.NotNull(xmlReaders, "xmlReaders");

            var composite = MetadataArtifactLoader.CreateCompositeFromXmlReaders(xmlReaders);

            Init(
                edmCollection,
                storeCollection,
                composite.GetReaders(), // filter out duplicates
                composite.GetPaths(),
                true /* throwOnError*/);
        }
        public StorageMappingItemCollection(
            EdmItemCollection edmCollection, StoreItemCollection storeCollection,
            params string[] filePaths)
            : base(DataSpace.CSSpace)
        {
            Check.NotNull(edmCollection, "edmCollection");
            Check.NotNull(storeCollection, "storeCollection");
            Check.NotNull(filePaths, "filePaths");

            _edmCollection = edmCollection;
            _storeItemCollection = storeCollection;

            // Wrap the file paths in instances of the MetadataArtifactLoader class, which provides
            // an abstraction and a uniform interface over a diverse set of metadata artifacts.
            //
            MetadataArtifactLoader composite = null;
            List<XmlReader> readers = null;
            try
            {
                composite = MetadataArtifactLoader.CreateCompositeFromFilePaths(filePaths, XmlConstants.CSSpaceSchemaExtension);
                readers = composite.CreateReaders(DataSpace.CSSpace);

                Init(
                    edmCollection, storeCollection, readers,
                    composite.GetPaths(DataSpace.CSSpace), true /*throwOnError*/);
            }
            finally
            {
                if (readers != null)
                {
                    Helper.DisposeXmlReaders(readers);
                }
            }
        }
 protected override bool DbDatabaseExists(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection)
 {
     throw new NotSupportedException("Checking database existence is not supported in NuoDB driver.");
 }
 protected override void DbDeleteDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection)
 {
     throw new NotSupportedException("Deleting database is not supported in NuoDB driver.");
 }
        // <summary>
        // Initializer that takes in a list of XmlReaders and creates metadata for mapping
        // in all the files.
        // </summary>
        // <param name="edmCollection"> The edm metadata collection that this mapping is to use </param>
        // <param name="storeCollection"> The store metadata collection that this mapping is to use </param>
        // <param name="xmlReaders"> The XmlReaders to load mapping from </param>
        // <param name="filePaths"> Mapping URIs </param>
        private IList<EdmSchemaError> Init(
            EdmItemCollection edmCollection,
            StoreItemCollection storeCollection,
            IEnumerable<XmlReader> xmlReaders,
            IList<string> filePaths,
            bool throwOnError)
        {
            DebugCheck.NotNull(xmlReaders);
            DebugCheck.NotNull(edmCollection);
            DebugCheck.NotNull(storeCollection);

            _edmCollection = edmCollection;
            _storeItemCollection = storeCollection;

            Dictionary<EntitySetBase, GeneratedView> userDefinedQueryViewsDict;
            Dictionary<OfTypeQVCacheKey, GeneratedView> userDefinedQueryViewsOfTypeDict;

            m_viewDictionary = new ViewDictionary(this, out userDefinedQueryViewsDict, out userDefinedQueryViewsOfTypeDict);

            var errors = new List<EdmSchemaError>();

            if (_edmCollection.EdmVersion != XmlConstants.UndefinedVersion
                && _storeItemCollection.StoreSchemaVersion != XmlConstants.UndefinedVersion
                && _edmCollection.EdmVersion != _storeItemCollection.StoreSchemaVersion)
            {
                errors.Add(
                    new EdmSchemaError(
                        Strings.Mapping_DifferentEdmStoreVersion,
                        (int)MappingErrorCode.MappingDifferentEdmStoreVersion, EdmSchemaErrorSeverity.Error));
            }
            else
            {
                var expectedVersion = _edmCollection.EdmVersion != XmlConstants.UndefinedVersion
                                          ? _edmCollection.EdmVersion
                                          : _storeItemCollection.StoreSchemaVersion;
                errors.AddRange(
                    LoadItems(xmlReaders, filePaths, userDefinedQueryViewsDict, userDefinedQueryViewsOfTypeDict, expectedVersion));
            }

            Debug.Assert(errors != null);

            if (errors.Count > 0 && throwOnError)
            {
                if (!MetadataHelper.CheckIfAllErrorsAreWarnings(errors))
                {
                    // NOTE: not using Strings.InvalidSchemaEncountered because it will truncate the errors list.
                    throw new MappingException(
                        String.Format(
                            CultureInfo.CurrentCulture,
                            EntityRes.GetString(EntityRes.InvalidSchemaEncountered),
                            Helper.CombineErrorMessage(errors)));
                }
            }

            return errors;
        }
        /// <summary>
        /// Factory method that creates a <see cref="StorageMappingItemCollection" />.
        /// </summary>
        /// <param name="edmItemCollection">
        /// The edm metadata collection to map. Must not be <c>null</c>.
        /// </param>
        /// <param name="storeItemCollection">
        /// The store metadata collection to map. Must not be <c>null</c>.
        /// </param>
        /// <param name="xmlReaders">
        /// MSL artifacts to load. Must not be <c>null</c>.
        /// </param>
        /// <param name="filePaths">
        /// Paths to MSL artifacts. Used in error messages. Can be <c>null</c> in which case
        /// the base Uri of the XmlReader will be used as a path.
        /// </param>
        /// <param name="errors">
        /// The collection of errors encountered while loading.
        /// </param>
        /// <returns>
        /// <see cref="EdmItemCollection" /> instance if no errors encountered. Otherwise <c>null</c>.
        /// </returns>
        public static StorageMappingItemCollection Create(
            EdmItemCollection edmItemCollection,
            StoreItemCollection storeItemCollection,
            IEnumerable<XmlReader> xmlReaders,
            IList<string> filePaths,
            out IList<EdmSchemaError> errors)
        {
            Check.NotNull(edmItemCollection, "edmItemCollection");
            Check.NotNull(storeItemCollection, "storeItemCollection");
            Check.NotNull(xmlReaders, "xmlReaders");
            EntityUtil.CheckArgumentContainsNull(ref xmlReaders, "xmlReaders");
            // filePaths is allowed to be null

            var storageMappingItemCollection
                = new StorageMappingItemCollection(edmItemCollection, storeItemCollection, xmlReaders, filePaths, out errors);

            return errors != null && errors.Count > 0 ? null : storageMappingItemCollection;
        }
        private static StorageMappingItemCollection LoadMsl(EdmItemCollection edmItemCollection, StoreItemCollection storeItemCollection)
        {
            IList <EdmSchemaError> errors;

            return(StorageMappingItemCollection.Create(
                       edmItemCollection,
                       storeItemCollection,
                       new[] { XDocument.Parse(Msl).CreateReader() },
                       null,
                       out errors));
        }