private static MetadataWorkspace CreateWorkSpace() { string sql = @"select csdl,msl,ssdl from Chapter7.Definitions"; XmlReader csdlReader = null; XmlReader mslReader = null; XmlReader ssdlReader = null; using (var cn = new SqlConnection(connString)) { using (var cmd = new SqlCommand(sql, cn)) { cn.Open(); var reader = cmd.ExecuteReader(); if (reader.Read()) { csdlReader = reader.GetSqlXml(0).CreateReader(); mslReader = reader.GetSqlXml(1).CreateReader(); ssdlReader = reader.GetSqlXml(2).CreateReader(); } } } var workspace = new MetadataWorkspace(); var edmCollection = new EdmItemCollection(new XmlReader[] { csdlReader }); var ssdlCollection = new StoreItemCollection(new XmlReader[] { ssdlReader }); var mappingCollection = new StorageMappingItemCollection(edmCollection, ssdlCollection, new XmlReader[] { mslReader }); workspace.RegisterItemCollection(edmCollection); workspace.RegisterItemCollection(ssdlCollection); workspace.RegisterItemCollection(mappingCollection); return(workspace); }
public static MetadataWorkspace CreateFakeMetadataWorkspace() { EdmItemCollection edmItemCollection; StoreItemCollection storeItemCollection; StorageMappingItemCollection mappingItemCollection; using (var reader = XmlReader.Create(new StringReader(Csdl))) { edmItemCollection = new EdmItemCollection(new [] { reader }); } using (var reader = XmlReader.Create(new StringReader(Ssdl))) { storeItemCollection = new StoreItemCollection(new[] { reader }); } using (var reader = XmlReader.Create(new StringReader(Msl))) { mappingItemCollection = new StorageMappingItemCollection( edmItemCollection, storeItemCollection, new [] { reader }); } return(new MetadataWorkspace( () => edmItemCollection, () => storeItemCollection, () => mappingItemCollection)); }
private GeneratedView( EntitySetBase extent, EdmType type, DbQueryCommandTree commandTree, string eSQL, DiscriminatorMap discriminatorMap, StorageMappingItemCollection mappingItemCollection, ConfigViewGenerator config) { this.m_extent = extent; this.m_type = type; this.m_commandTree = commandTree; this.m_eSQL = eSQL; this.m_discriminatorMap = discriminatorMap; this.m_mappingItemCollection = mappingItemCollection; this.m_config = config; if (!this.m_config.IsViewTracing) { return; } StringBuilder builder = new StringBuilder(1024); this.ToCompactString(builder); Helpers.FormatTraceLine("CQL view for {0}", (object)builder.ToString()); }
/// <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="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 IEnumerable <string> metadataResourcePaths = FindMetadataResources(contextType.Assembly); IEnumerable <MetadataWorkspaceInfo> 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) { EdmItemCollection edmItemCollection = new EdmItemCollection(workspaceInfo.Csdl); Type currentType = contextType; while (currentType != baseContextType && currentType != typeof(object)) { EntityContainer container; if (edmItemCollection.TryGetEntityContainer(currentType.Name, out container)) { StoreItemCollection store = new StoreItemCollection(workspaceInfo.Ssdl); StorageMappingItemCollection mapping = new StorageMappingItemCollection(edmItemCollection, store, workspaceInfo.Msl); MetadataWorkspace workspace = new MetadataWorkspace(); workspace.RegisterItemCollection(edmItemCollection); workspace.RegisterItemCollection(store); workspace.RegisterItemCollection(mapping); workspace.RegisterItemCollection(new ObjectItemCollection()); return(workspace); } currentType = currentType.BaseType; } } return(null); }
/// <summary> /// 设置数据库初始化,策略为自动迁移到最新版本 /// </summary> public static void Initialize() { CodeFirstDbContext context = new CodeFirstDbContext(); IDatabaseInitializer <CodeFirstDbContext> initializer; if (!context.Database.Exists()) { initializer = new CreateDatabaseIfNotExistsWithSeed(); } else { initializer = new NullDatabaseInitializer <CodeFirstDbContext>(); // initializer = new MigrateDatabaseToLatestVersion<CodeFirstDbContext, MigrationsConfiguration>(); } Database.SetInitializer(initializer); //EF预热,解决EF6第一次加载慢的问题 ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext; StorageMappingItemCollection mappingItemCollection = (StorageMappingItemCollection)objectContext.ObjectStateManager .MetadataWorkspace.GetItemCollection(DataSpace.CSSpace); mappingItemCollection.GenerateViews(new List <EdmSchemaError>()); context.Dispose(); }
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 void Prepare_returns_a_new_instance() { var objectQueryExecutionPlanFactory = new ObjectQueryExecutionPlanFactory( Common.Internal.Materialization.MockHelper.CreateTranslator <object>()); var edmItemCollection = new EdmItemCollection(); var fakeSqlProviderManifest = FakeSqlProviderServices.Instance.GetProviderManifest("2008"); var storeItemCollection = new StoreItemCollection(FakeSqlProviderFactory.Instance, fakeSqlProviderManifest, "System.Data.SqlClient", "2008"); var mappingItemCollection = new StorageMappingItemCollection(edmItemCollection, storeItemCollection, Enumerable.Empty <XmlReader>()); var metadataWorkspace = new MetadataWorkspace( () => edmItemCollection, () => storeItemCollection, () => mappingItemCollection); 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, useDatabaseNullSemantics: true); var parameters = new List <Tuple <ObjectParameter, QueryParameterExpression> >(); var objectQueryExecutionPlan = objectQueryExecutionPlanFactory.Prepare( objectContext, dbQueryCommandTree, typeof(object), MergeOption.NoTracking, false, new Span(), parameters, aliasGenerator: null); Assert.NotNull(objectQueryExecutionPlan); }
private static MetadataWorkspace CreateWrappedMetadataWorkspace(string metadata, IEnumerable <string> wrapperProviderNames) { MetadataWorkspace workspace = new MetadataWorkspace(); // parse Metadata keyword and load CSDL,SSDL,MSL files into XElement structures... var csdl = new List <XElement>(); var ssdl = new List <XElement>(); var msl = new List <XElement>(); ParseMetadata(metadata, csdl, ssdl, msl); // fix all SSDL files by changing 'Provider' to our provider and modifying foreach (var ssdlFile in ssdl) { foreach (string providerName in wrapperProviderNames) { ssdlFile.Attribute("ProviderManifestToken").Value = ssdl[0].Attribute("Provider").Value + ";" + ssdlFile.Attribute("ProviderManifestToken").Value; ssdlFile.Attribute("Provider").Value = providerName; } } // load item collections from XML readers created from XElements... EdmItemCollection eic = new EdmItemCollection(csdl.Select(c => c.CreateReader())); StoreItemCollection sic = new StoreItemCollection(ssdl.Select(c => c.CreateReader())); StorageMappingItemCollection smic = new StorageMappingItemCollection(eic, sic, msl.Select(c => c.CreateReader())); // and create metadata workspace based on them. workspace = new MetadataWorkspace(); workspace.RegisterItemCollection(eic); workspace.RegisterItemCollection(sic); workspace.RegisterItemCollection(smic); return(workspace); }
static internal DbExpression CompileFunctionView( string viewDef, StorageMappingItemCollection mappingItemCollection, ParserOptions.CompilationMode compilationMode, IEnumerable<DbParameterReferenceExpression> parameters) { Debug.Assert(!String.IsNullOrEmpty(viewDef), "!String.IsNullOrEmpty(viewDef)"); Debug.Assert(mappingItemCollection != null, "mappingItemCollection != null"); Perspective perspective = new TargetPerspective(mappingItemCollection.Workspace); ParserOptions parserOptions = new ParserOptions(); parserOptions.ParserCompilationMode = compilationMode; // Parameters have to be accessible in the body as regular scope variables, not as command parameters. // Hence compile view as lambda with parameters as lambda vars, then invoke the lambda specifying // command parameters as values of the lambda vars. DbLambda functionBody = CqlQuery.CompileQueryCommandLambda( viewDef, perspective, parserOptions, null /* parameters */, parameters.Select(pInfo => pInfo.ResultType.Variable(pInfo.ParameterName))); Debug.Assert(functionBody != null, "functionBody != null"); DbExpression expr = functionBody.Invoke(parameters); return expr; }
internal static StorageMappingItemCollection CreateStorageMappingItemCollection(string ssdl, string csdl, string msl) { StoreItemCollection storeCollection; EdmItemCollection edmCollection; StorageMappingItemCollection mappingCollection; using (var stringReader = new StringReader(ssdl)) using (var xmlReader = XmlReader.Create(stringReader)) { storeCollection = new StoreItemCollection(new[] { xmlReader }); } using (var stringReader = new StringReader(csdl)) using (var xmlReader = XmlReader.Create(stringReader)) { edmCollection = new EdmItemCollection(new[] { xmlReader }); } using (var stringReader = new StringReader(msl)) using (var xmlReader = XmlReader.Create(stringReader)) { mappingCollection = new StorageMappingItemCollection(edmCollection, storeCollection, new[] { xmlReader }); } return(mappingCollection); }
private GeneratedView( EntitySetBase extent, EdmType type, DbQueryCommandTree commandTree, string eSQL, DiscriminatorMap discriminatorMap, StorageMappingItemCollection mappingItemCollection, ConfigViewGenerator config) { // At least one of the commandTree or eSQL must be specified. // Both are specified in the case of user-defined views. Debug.Assert(commandTree != null || !String.IsNullOrEmpty(eSQL), "commandTree or eSQL must be specified"); m_extent = extent; m_type = type; m_commandTree = commandTree; m_eSQL = eSQL; m_discriminatorMap = discriminatorMap; m_mappingItemCollection = mappingItemCollection; m_config = config; if (m_config.IsViewTracing) { var trace = new StringBuilder(1024); ToCompactString(trace); Helpers.FormatTraceLine("CQL view for {0}", trace.ToString()); } }
public void Workspace_returns_a_new_workspace_with_all_collections_registered() { var edmItemCollection = new EdmItemCollection(new[] { XDocument.Parse(Csdl).CreateReader() }); var storeItemCollection = new StoreItemCollection(new[] { XDocument.Parse(Ssdl).CreateReader() }); IList <EdmSchemaError> errors; var storageMappingItemCollection = StorageMappingItemCollection.Create( edmItemCollection, storeItemCollection, new[] { XDocument.Parse(Msl).CreateReader() }, null, out errors); var workspace = storageMappingItemCollection.Workspace; 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); }
// <summary> // Creates generated view object for the combination of the <paramref name="extent" /> and the <paramref name="type" />. // This constructor is used for regular cell-based view generation. // </summary> internal static GeneratedView CreateGeneratedView( EntitySetBase extent, EdmType type, DbQueryCommandTree commandTree, string eSQL, StorageMappingItemCollection mappingItemCollection, ConfigViewGenerator config) { // If config.GenerateEsql is specified, eSQL must be non-null. // If config.GenerateEsql is false, commandTree is non-null except the case when loading pre-compiled eSQL views. Debug.Assert(!config.GenerateEsql || !String.IsNullOrEmpty(eSQL), "eSQL must be specified"); DiscriminatorMap discriminatorMap = null; if (commandTree != null) { commandTree = ViewSimplifier.SimplifyView(extent, commandTree); // See if the view matches the "discriminated" pattern (allows simplification of generated store commands) if (extent.BuiltInTypeKind == BuiltInTypeKind.EntitySet) { if (DiscriminatorMap.TryCreateDiscriminatorMap((EntitySet)extent, commandTree.Query, out discriminatorMap)) { Debug.Assert(discriminatorMap != null, "discriminatorMap == null after it has been created"); } } } return(new GeneratedView(extent, type, commandTree, eSQL, discriminatorMap, mappingItemCollection, config)); }
private static StorageMappingItemCollection LoadMappingItemCollection( DbProviderManifest providerManifest, string mslName, EdmItemCollection edmItemCollection, StoreItemCollection storeItemCollection) { using (var mslReader = providerManifest.GetInformation(mslName)) { IList <EdmSchemaError> errors; var mappingItemCollection = StorageMappingItemCollection.Create( edmItemCollection, storeItemCollection, new[] { mslReader }, new ReadOnlyCollection <string>( new List <string> { GetProviderServicesInformationLocationPath( providerManifest.GetType().Assembly.FullName, mslName) }), out errors); ThrowOnError(errors); return(mappingItemCollection); } }
private static MetadataWorkspace CreateMetadataWorkspace() { const string ssdl = @"<Schema Namespace=""NorthwindEF5Model.Store"" Provider=""System.Data.SqlClient"" ProviderManifestToken=""2008"" Alias=""Self"" xmlns=""http://schemas.microsoft.com/ado/2009/11/edm/ssdl"" xmlns:store=""http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator"">" + @" <EntityType Name=""Customers"">" + @" <Key>" + @" <PropertyRef Name=""CustomerID"" />" + @" </Key>" + @" <Property Name=""CustomerID"" Type=""nchar"" MaxLength=""5"" Nullable=""false"" />" + @" <Property Name=""CompanyName"" Type=""nvarchar"" MaxLength=""40"" Nullable=""false"" />" + @" </EntityType>" + @" <EntityContainer Name=""Container"" />" + @"</Schema>"; const string csdl = @"<Schema xmlns=""http://schemas.microsoft.com/ado/2009/11/edm"" Namespace=""dummy"">" + @" <EntityContainer Name=""DummyContainer""/>" + @"</Schema>"; const string msl = @"<Mapping Space=""C-S"" xmlns=""http://schemas.microsoft.com/ado/2009/11/mapping/cs"">" + @" <EntityContainerMapping StorageEntityContainer=""Container"" CdmEntityContainer=""DummyContainer"" />" + @"</Mapping>"; var storeItemCollection = Utils.CreateStoreItemCollection(ssdl); var edmItemCollection = new EdmItemCollection(new[] { XmlReader.Create(new StringReader(csdl)) }); var mappingItemCollection = new StorageMappingItemCollection( edmItemCollection, storeItemCollection, new[] { XmlReader.Create(new StringReader(msl)) }); return(new MetadataWorkspace(() => edmItemCollection, () => storeItemCollection, () => mappingItemCollection)); }
public void Workspace_can_be_constructed_when_EDM_identifiers_start_with_underscores() { var edmItemCollection = new EdmItemCollection(new[] { XDocument.Parse(UnderpantsCsdl).CreateReader() }); var storeItemCollection = new StoreItemCollection(new[] { XDocument.Parse(UnderpantsSsdl).CreateReader() }); IList<EdmSchemaError> errors; var storageMappingItemCollection = StorageMappingItemCollection.Create( edmItemCollection, storeItemCollection, new[] { XDocument.Parse(UnderpantsMsl).CreateReader() }, null, out errors); Assert.Equal(0, errors.Count); Assert.NotNull(storageMappingItemCollection); var workspace = new MetadataWorkspace( () => edmItemCollection, () => storeItemCollection, () => storageMappingItemCollection); // Run enough initialization to get validation done using (var connection = new EntityConnection(workspace, new SqlConnection())) { Assert.Same(edmItemCollection, connection.GetMetadataWorkspace().GetItemCollection(DataSpace.CSpace)); Assert.Same(storeItemCollection, connection.GetMetadataWorkspace().GetItemCollection(DataSpace.SSpace)); Assert.Same(storageMappingItemCollection, connection.GetMetadataWorkspace().GetItemCollection(DataSpace.CSSpace)); } }
internal FunctionImportMappingComposable( EdmFunction functionImport, EdmFunction targetFunction, List <Tuple <StructuralType, List <StorageConditionPropertyMapping>, List <StoragePropertyMapping> > > structuralTypeMappings, EdmProperty[] targetFunctionKeys, StorageMappingItemCollection mappingItemCollection) : base(functionImport, targetFunction) { DebugCheck.NotNull(mappingItemCollection); Debug.Assert(functionImport.IsComposableAttribute, "functionImport.IsComposableAttribute"); Debug.Assert(targetFunction.IsComposableAttribute, "targetFunction.IsComposableAttribute"); Debug.Assert( functionImport.EntitySet == null || structuralTypeMappings != null, "Function import returning entities must have structuralTypeMappings."); Debug.Assert( structuralTypeMappings == null || structuralTypeMappings.Count > 0, "Non-null structuralTypeMappings must not be empty."); EdmType resultType; Debug.Assert( structuralTypeMappings != null || MetadataHelper.TryGetFunctionImportReturnType(functionImport, 0, out resultType) && TypeSemantics.IsScalarType(resultType), "Either type mappings should be specified or the function import should be Collection(Scalar)."); Debug.Assert( functionImport.EntitySet == null || targetFunctionKeys != null, "Keys must be inferred for a function import returning entities."); Debug.Assert(targetFunctionKeys == null || targetFunctionKeys.Length > 0, "Keys must be null or non-empty."); m_mappingItemCollection = mappingItemCollection; // We will use these parameters to target s-space function calls in the generated command tree. // Since enums don't exist in s-space we need to use the underlying type. m_commandParameters = functionImport.Parameters.Select(p => TypeHelpers.GetPrimitiveTypeUsageForScalar(p.TypeUsage).Parameter(p.Name)).ToArray(); m_structuralTypeMappings = structuralTypeMappings; m_targetFunctionKeys = targetFunctionKeys; }
/// <summary> /// Creates generated view object for the combination of the <paramref name="extent"/> and the <paramref name="type"/>. /// This constructor is used for regular cell-based view generation. /// </summary> internal static GeneratedView CreateGeneratedView(EntitySetBase extent, EdmType type, DbQueryCommandTree commandTree, string eSQL, StorageMappingItemCollection mappingItemCollection, ConfigViewGenerator config) { // If config.GenerateEsql is specified, eSQL must be non-null. // If config.GenerateEsql is false, commandTree is non-null except the case when loading pre-compiled eSQL views. Debug.Assert(!config.GenerateEsql || !String.IsNullOrEmpty(eSQL), "eSQL must be specified"); DiscriminatorMap discriminatorMap = null; if (commandTree != null) { commandTree = ViewSimplifier.SimplifyView(extent, commandTree); // See if the view matches the "discriminated" pattern (allows simplification of generated store commands) if (extent.BuiltInTypeKind == BuiltInTypeKind.EntitySet) { if (DiscriminatorMap.TryCreateDiscriminatorMap((EntitySet)extent, commandTree.Query, out discriminatorMap)) { Debug.Assert(discriminatorMap != null, "discriminatorMap == null after it has been created"); } } } return new GeneratedView(extent, type, commandTree, eSQL, discriminatorMap, mappingItemCollection, config); }
private static MetadataWorkspace CreateEdmxBasedWorkspace(DbContext context) { var edmxBuilder = new StringBuilder(); EdmxWriter.WriteEdmx(context, XmlWriter.Create(edmxBuilder)); var edmx = XDocument.Parse(edmxBuilder.ToString()); var edmItemCollection = new EdmItemCollection( new[] { edmx.Descendants(XName.Get("Schema", "http://schemas.microsoft.com/ado/2009/11/edm")).Single().CreateReader() }); var storeItemCollection = new StoreItemCollection( new[] { edmx.Descendants(XName.Get("Schema", "http://schemas.microsoft.com/ado/2009/11/edm/ssdl")).Single().CreateReader() }); var mapping = new StorageMappingItemCollection( edmItemCollection, storeItemCollection, new[] { new XElement(edmx.Descendants(XName.Get("Mapping", "http://schemas.microsoft.com/ado/2009/11/mapping/cs")).Single()) .CreateReader() }); return(new MetadataWorkspace(() => edmItemCollection, () => storeItemCollection, () => mapping)); }
internal static DbExpression CompileFunctionView( string viewDef, StorageMappingItemCollection mappingItemCollection, ParserOptions.CompilationMode compilationMode, IEnumerable <DbParameterReferenceExpression> parameters) { DebugCheck.NotEmpty(viewDef); DebugCheck.NotNull(mappingItemCollection); Perspective perspective = new TargetPerspective(mappingItemCollection.Workspace); var parserOptions = new ParserOptions(); parserOptions.ParserCompilationMode = compilationMode; // Parameters have to be accessible in the body as regular scope variables, not as command parameters. // Hence compile view as lambda with parameters as lambda vars, then invoke the lambda specifying // command parameters as values of the lambda vars. var functionBody = CqlQuery.CompileQueryCommandLambda( viewDef, perspective, parserOptions, null /* parameters */, parameters.Select(pInfo => pInfo.ResultType.Variable(pInfo.ParameterName))); Debug.Assert(functionBody != null, "functionBody != null"); DbExpression expr = functionBody.Invoke(parameters); return(expr); }
/// <summary>Initializes a new EntityContainerMapping instance.</summary> /// <param name="conceptualEntityContainer">The conceptual entity container to be mapped.</param> /// <param name="storeEntityContainer">The store entity container to be mapped.</param> /// <param name="mappingItemCollection">The parent mapping item collection.</param> /// <param name="generateUpdateViews">Flag indicating whether to generate update views.</param> public EntityContainerMapping( EntityContainer conceptualEntityContainer, EntityContainer storeEntityContainer, StorageMappingItemCollection mappingItemCollection, bool generateUpdateViews) : this(conceptualEntityContainer, storeEntityContainer, mappingItemCollection, true, generateUpdateViews) { }
/// <summary> /// Creates generated view object for the combination of the <paramref name="extent"/> and the <paramref name="type"/>. /// This constructor is used for FK association sets only. /// </summary> internal static GeneratedView CreateGeneratedViewForFKAssociationSet(EntitySetBase extent, EdmType type, DbQueryCommandTree commandTree, StorageMappingItemCollection mappingItemCollection, ConfigViewGenerator config) { return(new GeneratedView(extent, type, commandTree, null, null, mappingItemCollection, config)); }
public void StorageMappingItemCollection_Create_factory_method_throws_for_null_edmItemCollection() { IList <EdmSchemaError> errors; Assert.Equal("edmItemCollection", Assert.Throws <ArgumentNullException>( () => StorageMappingItemCollection.Create(null, null, null, null, out errors)).ParamName); }
/// <summary> /// Creates generated view object for the combination of the <paramref name="extent"/> and the <paramref name="type"/>. /// This constructor is used for FK association sets only. /// </summary> internal static GeneratedView CreateGeneratedViewForFKAssociationSet(EntitySetBase extent, EdmType type, DbQueryCommandTree commandTree, StorageMappingItemCollection mappingItemCollection, ConfigViewGenerator config) { return new GeneratedView(extent, type, commandTree, null, null, mappingItemCollection, config); }
internal void LoadStoreCollection(EdmItemCollection edmItemCollection, MetadataArtifactLoader loader) { StoreItemCollection storeItemCollection = null; IEnumerable <XmlReader> sSpaceXmlReaders = loader.CreateReaders(DataSpace.SSpace); try { // Load the store side, however, only do so if we don't already have one storeItemCollection = new StoreItemCollection( sSpaceXmlReaders, loader.GetPaths(DataSpace.SSpace)); } finally { Helper.DisposeXmlReaders(sSpaceXmlReaders); } // If this entry is getting re-used, make sure that the previous query cache manager gets // cleared up if (_queryCacheManager != null) { _queryCacheManager.Clear(); } // Update the query cache manager reference _queryCacheManager = storeItemCollection.QueryCacheManager; // With the store metadata in place, we can then load the mappings, however, only use it // if we don't already have one // StorageMappingItemCollection storageMappingItemCollection = null; IEnumerable <XmlReader> csSpaceXmlReaders = loader.CreateReaders(DataSpace.CSSpace); try { storageMappingItemCollection = new StorageMappingItemCollection( edmItemCollection, storeItemCollection, csSpaceXmlReaders, loader.GetPaths(DataSpace.CSSpace)); } finally { Helper.DisposeXmlReaders(csSpaceXmlReaders); } List <string> permissionPaths = new List <string>(); loader.CollectFilePermissionPaths(permissionPaths, DataSpace.SSpace); loader.CollectFilePermissionPaths(permissionPaths, DataSpace.CSSpace); FileIOPermission filePermissions = null; if (permissionPaths.Count > 0) { filePermissions = new FileIOPermission(FileIOPermissionAccess.Read, permissionPaths.ToArray()); } this.UpdateMetadataEntry(storageMappingItemCollection, filePermissions); }
// virtual for mocking internal virtual Dictionary <EntitySetBase, DbMappingView> GenerateViews( StorageMappingItemCollection mappingItemCollection, string conceptualModelContainerName, string storeModelContainerName) { var errors = new List <EdmSchemaError>(); return(mappingItemCollection.GenerateViews(conceptualModelContainerName, storeModelContainerName, errors)); }
/// <summary> /// Creates generated view object for the combination of the <paramref name="setMapping"/>.Set and the <paramref name="type"/>. /// This constructor is used for user-defined query views only. /// </summary> internal static bool TryParseUserSpecifiedView(StorageSetMapping setMapping, EntityTypeBase type, string eSQL, bool includeSubtypes, StorageMappingItemCollection mappingItemCollection, ConfigViewGenerator config, /*out*/ IList <EdmSchemaError> errors, out GeneratedView generatedView) { bool failed = false; DbQueryCommandTree commandTree; DiscriminatorMap discriminatorMap; Exception parserException; if (!GeneratedView.TryParseView(eSQL, true, setMapping.Set, mappingItemCollection, config, out commandTree, out discriminatorMap, out parserException)) { EdmSchemaError error = new EdmSchemaError(System.Data.Entity.Strings.Mapping_Invalid_QueryView2(setMapping.Set.Name, parserException.Message), (int)StorageMappingErrorCode.InvalidQueryView, EdmSchemaErrorSeverity.Error, setMapping.EntityContainerMapping.SourceLocation, setMapping.StartLineNumber, setMapping.StartLinePosition, parserException); errors.Add(error); failed = true; } else { Debug.Assert(commandTree != null, "commandTree not set after parsing the view"); // Verify that all expressions appearing in the view are supported. foreach (var error in ViewValidator.ValidateQueryView(commandTree, setMapping, type, includeSubtypes)) { errors.Add(error); failed = true; } // Verify that the result type of the query view is assignable to the element type of the entityset CollectionType queryResultType = (commandTree.Query.ResultType.EdmType) as CollectionType; if ((queryResultType == null) || (!setMapping.Set.ElementType.IsAssignableFrom(queryResultType.TypeUsage.EdmType))) { EdmSchemaError error = new EdmSchemaError(System.Data.Entity.Strings.Mapping_Invalid_QueryView_Type(setMapping.Set.Name), (int)StorageMappingErrorCode.InvalidQueryViewResultType, EdmSchemaErrorSeverity.Error, setMapping.EntityContainerMapping.SourceLocation, setMapping.StartLineNumber, setMapping.StartLinePosition); errors.Add(error); failed = true; } } if (!failed) { generatedView = new GeneratedView(setMapping.Set, type, commandTree, eSQL, discriminatorMap, mappingItemCollection, config); return(true); } else { generatedView = null; return(false); } }
private static void ValidateAndGenerateViews(FileInfo edmxFile, LanguageOption languageOption, bool generateViews) { XDocument xdoc = XDocument.Load(edmxFile.FullName); XElement c = GetCsdlFromEdmx(xdoc); XElement s = GetSsdlFromEdmx(xdoc); XElement m = GetMslFromEdmx(xdoc); Version v = _namespaceManager.GetVersionFromEDMXDocument(xdoc); // load the csdl XmlReader[] cReaders = { c.CreateReader() }; IList <EdmSchemaError> cErrors = null; EdmItemCollection edmItemCollection = MetadataItemCollectionFactory.CreateEdmItemCollection(cReaders, out cErrors); // load the ssdl XmlReader[] sReaders = { s.CreateReader() }; IList <EdmSchemaError> sErrors = null; StoreItemCollection storeItemCollection = MetadataItemCollectionFactory.CreateStoreItemCollection(sReaders, out sErrors); // load the msl XmlReader[] mReaders = { m.CreateReader() }; IList <EdmSchemaError> mErrors = null; StorageMappingItemCollection mappingItemCollection = MetadataItemCollectionFactory.CreateStorageMappingItemCollection( edmItemCollection, storeItemCollection, mReaders, out mErrors); // either pre-compile views or validate the mappings IList <EdmSchemaError> viewGenerationErrors = null; if (generateViews) { // generate views & write them out to a file string outputFile = GetFileNameWithNewExtension(edmxFile, ".GeneratedViews" + GetFileExtensionForLanguageOption(languageOption)); EntityViewGenerator evg = new EntityViewGenerator(languageOption); using (var file = File.OpenWrite(outputFile)) { using (var writer = new StreamWriter(file)) { viewGenerationErrors = evg.GenerateViews(mappingItemCollection, writer, v); } } } else { viewGenerationErrors = EntityViewGenerator.Validate(mappingItemCollection, v); } // write errors WriteErrors(cErrors); WriteErrors(sErrors); WriteErrors(mErrors); WriteErrors(viewGenerationErrors); }
public IList <EdmSchemaError> GenerateViews(StorageMappingItemCollection mappingCollection, TextWriter outputWriter) { EDesignUtil.CheckArgumentNull(mappingCollection, "mappingCollection"); Version targetEntityFrameworkVersion; IList <EdmSchemaError> errorList = GetMinimumTargetFrameworkVersion(mappingCollection, out targetEntityFrameworkVersion); return(GenerateViews(mappingCollection, outputWriter, targetEntityFrameworkVersion).Concat(errorList).ToList()); }
public void MappingViewCacheFactory_can_be_set_and_retrieved() { var itemCollection = new StorageMappingItemCollection(); var factory = new SampleMappingViewCacheFactory("value"); itemCollection.MappingViewCacheFactory = factory; Assert.Same(factory, itemCollection.MappingViewCacheFactory); }
public static IList <EdmSchemaError> Validate(StorageMappingItemCollection mappingCollection) { EDesignUtil.CheckArgumentNull(mappingCollection, "mappingCollection"); Version targetEntityFrameworkVersion; IList <EdmSchemaError> errorList = GetMinimumTargetFrameworkVersion(mappingCollection, out targetEntityFrameworkVersion); return(Validate(mappingCollection, targetEntityFrameworkVersion).Concat(errorList).ToList()); }
/// <summary> /// Creates generated view object for the combination of the <paramref name="setMapping"/>.Set and the <paramref name="type"/>. /// This constructor is used for user-defined query views only. /// </summary> internal static bool TryParseUserSpecifiedView(StorageSetMapping setMapping, EntityTypeBase type, string eSQL, bool includeSubtypes, StorageMappingItemCollection mappingItemCollection, ConfigViewGenerator config, /*out*/ IList<EdmSchemaError> errors, out GeneratedView generatedView) { bool failed = false; DbQueryCommandTree commandTree; DiscriminatorMap discriminatorMap; Exception parserException; if (!GeneratedView.TryParseView(eSQL, true, setMapping.Set, mappingItemCollection, config, out commandTree, out discriminatorMap, out parserException)) { EdmSchemaError error = new EdmSchemaError(System.Data.Entity.Strings.Mapping_Invalid_QueryView2(setMapping.Set.Name, parserException.Message), (int)StorageMappingErrorCode.InvalidQueryView, EdmSchemaErrorSeverity.Error, setMapping.EntityContainerMapping.SourceLocation, setMapping.StartLineNumber, setMapping.StartLinePosition, parserException); errors.Add(error); failed = true; } else { Debug.Assert(commandTree != null, "commandTree not set after parsing the view"); // Verify that all expressions appearing in the view are supported. foreach (var error in ViewValidator.ValidateQueryView(commandTree, setMapping, type, includeSubtypes)) { errors.Add(error); failed = true; } // Verify that the result type of the query view is assignable to the element type of the entityset CollectionType queryResultType = (commandTree.Query.ResultType.EdmType) as CollectionType; if ((queryResultType == null) || (!setMapping.Set.ElementType.IsAssignableFrom(queryResultType.TypeUsage.EdmType))) { EdmSchemaError error = new EdmSchemaError(System.Data.Entity.Strings.Mapping_Invalid_QueryView_Type(setMapping.Set.Name), (int)StorageMappingErrorCode.InvalidQueryViewResultType, EdmSchemaErrorSeverity.Error, setMapping.EntityContainerMapping.SourceLocation, setMapping.StartLineNumber, setMapping.StartLinePosition); errors.Add(error); failed = true; } } if (!failed) { generatedView = new GeneratedView(setMapping.Set, type, commandTree, eSQL, discriminatorMap, mappingItemCollection, config); return true; } else { generatedView = null; return false; } }
public void StorageMappingItemCollection_Create_factory_method_throws_for_null_storeItemCollection() { var edmItemCollection = new EdmItemCollection(new[] { XDocument.Parse(Csdl).CreateReader() }); IList <EdmSchemaError> errors; Assert.Equal("storeItemCollection", Assert.Throws <ArgumentNullException>( () => StorageMappingItemCollection.Create(edmItemCollection, null, null, null, out errors)).ParamName); }
private bool GetViewsWithErrors(StorageMappingItemCollection mappingCollection, out CodeDomProvider provider, out IList <EdmSchemaError> schemaErrors, out Dictionary <EntitySetBase, string> generatedViews) { GetViewsAndCodeDomProvider(mappingCollection, out provider, out schemaErrors, out generatedViews); //If the generated views are empty because of errors or warnings, then don't create an output file. if (generatedViews.Count == 0 && schemaErrors.Count > 0) { return(true); } return(false); }
internal static DbCommandTree CompileView( string viewDef, StorageMappingItemCollection mappingItemCollection, ParserOptions.CompilationMode compilationMode) { DebugCheck.NotEmpty(viewDef); DebugCheck.NotNull(mappingItemCollection); Perspective perspective = new TargetPerspective(mappingItemCollection.Workspace); var parserOptions = new ParserOptions(); parserOptions.ParserCompilationMode = compilationMode; var expr = CqlQuery.Compile(viewDef, perspective, parserOptions, null).CommandTree; Debug.Assert(expr != null, "Compile returned empty tree?"); return expr; }
static internal DbCommandTree CompileView( string viewDef, StorageMappingItemCollection mappingItemCollection, ParserOptions.CompilationMode compilationMode) { Debug.Assert(!String.IsNullOrEmpty(viewDef), "!String.IsNullOrEmpty(viewDef)"); Debug.Assert(mappingItemCollection != null, "mappingItemCollection != null"); Perspective perspective = new TargetPerspective(mappingItemCollection.Workspace); ParserOptions parserOptions = new ParserOptions(); parserOptions.ParserCompilationMode = compilationMode; DbCommandTree expr = CqlQuery.Compile(viewDef, perspective, parserOptions, null).CommandTree; Debug.Assert(expr != null, "Compile returned empty tree?"); return expr; }
/// <summary> /// Given the generated <paramref name="view"/>, the <paramref name="caseStatements"/> for the multiconstant fields, /// the <paramref name="projectedSlotMap"/> that maps different paths of the entityset (for which the view is being generated) to slot indexes in the view, /// creates an object that is capable of generating the Cql for <paramref name="view"/>. /// </summary> internal CqlGenerator(CellTreeNode view, Dictionary<MemberPath, CaseStatement> caseStatements, CqlIdentifiers identifiers, MemberProjectionIndex projectedSlotMap, int numCellsInView, BoolExpression topLevelWhereClause, StorageMappingItemCollection mappingItemCollection) { m_view = view; m_caseStatements = caseStatements; m_projectedSlotMap = projectedSlotMap; m_numBools = numCellsInView; // We have that many booleans m_topLevelWhereClause = topLevelWhereClause; m_identifiers = identifiers; m_mappingItemCollection = mappingItemCollection; }
public static MetadataWorkspace CreateMetadataWorkspace(List<XElement> csdl, List<XElement> ssdl, List<XElement> msl) { EdmItemCollection eic = new EdmItemCollection(csdl.Select(c => c.CreateReader())); StoreItemCollection sic = new StoreItemCollection(ssdl.Select(c => c.CreateReader())); StorageMappingItemCollection smic = new StorageMappingItemCollection(eic, sic, msl.Select(c => c.CreateReader())); // and create metadata workspace based on them. #if !EFOLD MetadataWorkspace workspace = new MetadataWorkspace( () => eic, () => sic, () => smic); #else // Obsolete API MetadataWorkspace workspace = new MetadataWorkspace(); workspace.RegisterItemCollection(eic); workspace.RegisterItemCollection(sic); workspace.RegisterItemCollection(smic); #endif return workspace; }
private GeneratedView(EntitySetBase extent, EdmType type, DbQueryCommandTree commandTree, string eSQL, DiscriminatorMap discriminatorMap, StorageMappingItemCollection mappingItemCollection, ConfigViewGenerator config) { // At least one of the commandTree or eSQL must be specified. // Both are specified in the case of user-defined views. Debug.Assert(commandTree != null || !String.IsNullOrEmpty(eSQL), "commandTree or eSQL must be specified"); m_extent = extent; m_type = type; m_commandTree = commandTree; m_eSQL = eSQL; m_discriminatorMap = discriminatorMap; m_mappingItemCollection = mappingItemCollection; m_config = config; if (m_config.IsViewTracing) { StringBuilder trace = new StringBuilder(1024); this.ToCompactString(trace); Helpers.FormatTraceLine("CQL view for {0}", trace.ToString()); } }
/// <summary> /// Given an extent and its corresponding view, invokes the parser to check if the view definition is syntactically correct. /// Iff parsing succeeds: <paramref name="commandTree"/> and <paramref name="discriminatorMap"/> are set to the parse result and method returns true, /// otherwise if parser has thrown a catchable exception, it is returned via <paramref name="parserException"/> parameter, /// otherwise exception is re-thrown. /// </summary> private static bool TryParseView(string eSQL, bool isUserSpecified, EntitySetBase extent, StorageMappingItemCollection mappingItemCollection, ConfigViewGenerator config, out DbQueryCommandTree commandTree, out DiscriminatorMap discriminatorMap, out Exception parserException) { commandTree = null; discriminatorMap = null; parserException = null; // We do not catch any internal exceptions any more config.StartSingleWatch(PerfType.ViewParsing); try { // If it is a user specified view, allow all queries. Otherwise parse the view in the restricted mode. ParserOptions.CompilationMode compilationMode = ParserOptions.CompilationMode.RestrictedViewGenerationMode; if (isUserSpecified) { compilationMode = ParserOptions.CompilationMode.UserViewGenerationMode; } Debug.Assert(!String.IsNullOrEmpty(eSQL), "eSQL query is not specified"); commandTree = (DbQueryCommandTree)ExternalCalls.CompileView(eSQL, mappingItemCollection, compilationMode); // For non user-specified views, perform simplification. if (!isUserSpecified) { commandTree = ViewSimplifier.SimplifyView(extent, commandTree); } // See if the view matches the "discriminated" pattern (allows simplification of generated store commands) if (extent.BuiltInTypeKind == BuiltInTypeKind.EntitySet) { if (DiscriminatorMap.TryCreateDiscriminatorMap((EntitySet)extent, commandTree.Query, out discriminatorMap)) { Debug.Assert(discriminatorMap != null, "discriminatorMap == null after it has been created"); } } } catch (Exception e) { // Catching all the exception types since Query parser seems to be throwing veriety of // exceptions - EntityException, ArgumentException, ArgumentNullException etc. if (EntityUtil.IsCatchableExceptionType(e)) { parserException = e; } else { throw; } } finally { config.StopSingleWatch(PerfType.ViewParsing); } Debug.Assert(commandTree != null || parserException != null, "Either commandTree or parserException is expected."); // Note: m_commandTree might have been initialized by a previous call to this method, so in consequent calls it might occur that // both m_commandTree and parserException are not null - this would mean that the last parse attempt failed, but m_commandTree value is // preserved from the previous call. return parserException == null; }
private static MetadataWorkspace CreateWrappedMetadataWorkspace(string metadata, IEnumerable<string> wrapperProviderNames) { // parse Metadata keyword and load CSDL,SSDL,MSL files into XElement structures... var csdl = new List<XElement>(); var ssdl = new List<XElement>(); var msl = new List<XElement>(); ParseMetadata(metadata, csdl, ssdl, msl); // fix all SSDL files by changing 'Provider' to our provider and modifying foreach (var ssdlFile in ssdl) { foreach (string providerName in wrapperProviderNames) { ssdlFile.Attribute("ProviderManifestToken").Value = ssdl[0].Attribute("Provider").Value + ";" + ssdlFile.Attribute("ProviderManifestToken").Value; ssdlFile.Attribute("Provider").Value = providerName; } } // load item collections from XML readers created from XElements... EdmItemCollection eic = new EdmItemCollection(csdl.Select(c => c.CreateReader())); StoreItemCollection sic = new StoreItemCollection(ssdl.Select(c => c.CreateReader())); StorageMappingItemCollection smic = new StorageMappingItemCollection(eic, sic, msl.Select(c => c.CreateReader())); // and create metadata workspace based on them. #if !EFOLD MetadataWorkspace workspace = new MetadataWorkspace( () => eic, () => sic, () => smic); #else // Obsolete API MetadataWorkspace workspace = new MetadataWorkspace(); workspace.RegisterItemCollection(eic); workspace.RegisterItemCollection(sic); workspace.RegisterItemCollection(smic); #endif return workspace; }
/// <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="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 IEnumerable<string> metadataResourcePaths = FindMetadataResources(contextType.Assembly); IEnumerable<MetadataWorkspaceInfo> 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) { EdmItemCollection edmItemCollection = new EdmItemCollection(workspaceInfo.Csdl); Type currentType = contextType; while (currentType != baseContextType && currentType != typeof(object)) { EntityContainer container; if (edmItemCollection.TryGetEntityContainer(currentType.Name, out container)) { StoreItemCollection store = new StoreItemCollection(workspaceInfo.Ssdl); #if DBCONTEXT // This actually means EF6+ MetadataWorkspace workspace = new MetadataWorkspace( () => edmItemCollection, () => store, () => new StorageMappingItemCollection(edmItemCollection, store, workspaceInfo.Msl), () => new ObjectItemCollection()); #else // EF4 StorageMappingItemCollection mapping = new StorageMappingItemCollection(edmItemCollection, store, workspaceInfo.Msl); MetadataWorkspace workspace = new MetadataWorkspace(); workspace.RegisterItemCollection(edmItemCollection); workspace.RegisterItemCollection(store); workspace.RegisterItemCollection(mapping); workspace.RegisterItemCollection(new ObjectItemCollection()); #endif return workspace; } currentType = currentType.BaseType; } } return null; }