/// <summary>
        /// Constructs a grouper based on the contents of the given entity state manager.
        /// </summary>
        /// <param name="stateManager">Entity state manager containing changes to be processed.</param>
        /// <param name="metadataWorkspace">Metadata workspace.</param>
        /// <param name="connection">Map connection</param>
        /// <param name="commandTimeout">Timeout for update commands; null means 'use provider default'</param>
        private UpdateTranslator(IEntityStateManager stateManager, MetadataWorkspace metadataWorkspace, EntityConnection connection, int? commandTimeout)
        {
            EntityUtil.CheckArgumentNull(stateManager, "stateManager");
            EntityUtil.CheckArgumentNull(metadataWorkspace, "metadataWorkspace");
            EntityUtil.CheckArgumentNull(connection, "connection");

            // propagation state
            m_changes = new Dictionary<EntitySetBase, ChangeNode>();
            m_functionChanges = new Dictionary<EntitySetBase, List<ExtractedStateEntry>>();
            m_stateEntries = new List<IEntityStateEntry>();
            m_knownEntityKeys = new Set<EntityKey>();
            m_requiredEntities = new Dictionary<EntityKey, AssociationSet>();
            m_optionalEntities = new Set<EntityKey>();
            m_includedValueEntities = new Set<EntityKey>();

            // workspace state
            m_metadataWorkspace = metadataWorkspace;
            m_viewLoader = metadataWorkspace.GetUpdateViewLoader();
            m_stateManager = stateManager;

            // ancillary propagation services
            m_recordConverter = new RecordConverter(this);
            m_constraintValidator = new RelationshipConstraintValidator(this);

            m_providerServices = DbProviderServices.GetProviderServices(connection.StoreProviderFactory);
            m_connection = connection;
            m_commandTimeout = commandTimeout;

            // metadata cache
            m_extractorMetadata = new Dictionary<Tuple<EntitySetBase, StructuralType>, ExtractorMetadata>(); ;

            // key management
            KeyManager = new KeyManager(this);
            KeyComparer = CompositeKey.CreateComparer(KeyManager);
        }
Beispiel #2
0
        /// <summary>
        /// Retrieves a mapping to CLR type for the given EDM type. Assumes the MetadataWorkspace has no    
        /// </summary>
        internal static ObjectTypeMapping GetObjectMapping(EdmType type, MetadataWorkspace workspace)
        {
            // Check if the workspace has cspace item collection registered with it. If not, then its a case
            // of public materializer trying to create objects from PODR or EntityDataReader with no context.
            ItemCollection collection;
            if (workspace.TryGetItemCollection(DataSpace.CSpace, out collection))
            {
                return (ObjectTypeMapping)workspace.GetMap(type, DataSpace.OCSpace);
            }
            else
            {
                EdmType ospaceType;
                EdmType cspaceType;
                // If its a case of EntityDataReader with no context, the typeUsage which is passed in must contain
                // a cspace type. We need to look up an OSpace type in the ospace item collection and then create
                // ocMapping
                if (type.DataSpace == DataSpace.CSpace)
                {
                    // if its a primitive type, then the names will be different for CSpace type and OSpace type
                    if (Helper.IsPrimitiveType(type))
                    {
                        ospaceType = workspace.GetMappedPrimitiveType(((PrimitiveType)type).PrimitiveTypeKind, DataSpace.OSpace);
                    }
                    else
                    {
                        // Metadata will throw if there is no item with this identity present.
                        // Is this exception fine or does object materializer code wants to wrap and throw a new exception
                        ospaceType = workspace.GetItem<EdmType>(type.FullName, DataSpace.OSpace);
                    }
                    cspaceType = type;
                }
                else
                {
                    // In case of PODR, there is no cspace at all. We must create a fake ocmapping, with ospace types
                    // on both the ends
                    ospaceType = type;
                    cspaceType = type;
                }

                // This condition must be hit only when someone is trying to materialize a legacy data reader and we
                // don't have the CSpace metadata.
                if (!Helper.IsPrimitiveType(ospaceType) && !Helper.IsEntityType(ospaceType) && !Helper.IsComplexType(ospaceType))
                {
                    throw EntityUtil.MaterializerUnsupportedType();
                }

                ObjectTypeMapping typeMapping;

                if (Helper.IsPrimitiveType(ospaceType))
                {
                    typeMapping = new ObjectTypeMapping(ospaceType, cspaceType);
                }
                else
                {
                    typeMapping = DefaultObjectMappingItemCollection.LoadObjectMapping(cspaceType, ospaceType, null);
                }

                return typeMapping;
            }
        }
        internal DbDeleteCommandTree(MetadataWorkspace metadata, DataSpace dataSpace, DbExpressionBinding target, DbExpression predicate)
            : base(metadata, dataSpace, target)
        {
            EntityUtil.CheckArgumentNull(predicate, "predicate");

            this._predicate = predicate;
        }
 private IEnumerable<KeyValuePair<Shaper<RecordState>, CoordinatorFactory<RecordState>>> GetNextResultShaperInfo(
     DbDataReader storeDataReader, MetadataWorkspace workspace, IEnumerable<ColumnMap> nextResultColumnMaps)
 {
     // It is important to do this lazily as the storeDataReader will have advanced to the next result set
     // by the time this IEnumerable is advanced
     return nextResultColumnMaps.Select(nextResultColumnMap => CreateShaperInfo(storeDataReader, nextResultColumnMap, workspace));
 }
Beispiel #5
0
        /// <summary>
        /// Creates a new command
        /// </summary>
        internal Command(MetadataWorkspace metadataWorkspace)
        {
            m_parameterMap = new Dictionary<string, ParameterVar>();
            m_vars = new List<Var>();
            m_tables = new List<Table>();
            m_metadataWorkspace = metadataWorkspace;
            if(!TryGetPrimitiveType(PrimitiveTypeKind.Boolean, out m_boolType))
            {
                throw EntityUtil.ProviderIncompatible(System.Data.Entity.Strings.Cqt_General_NoProviderBooleanType);
            }
            if (!TryGetPrimitiveType(PrimitiveTypeKind.Int32, out m_intType))
            {
                throw EntityUtil.ProviderIncompatible(System.Data.Entity.Strings.Cqt_General_NoProviderIntegerType);
            }
            if (!TryGetPrimitiveType(PrimitiveTypeKind.String, out m_stringType))
            {
                throw EntityUtil.ProviderIncompatible(System.Data.Entity.Strings.Cqt_General_NoProviderStringType);
            }
            m_trueOp = new ConstantPredicateOp(m_boolType, true);
            m_falseOp = new ConstantPredicateOp(m_boolType, false);
            m_nodeInfoVisitor = new NodeInfoVisitor(this);
            m_keyPullupVisitor = new PlanCompiler.KeyPullup(this);

            // FreeLists
            m_freeVarVecEnumerators = new Stack<VarVec.VarVecEnumerator>();
            m_freeVarVecs = new Stack<VarVec>();

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

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

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

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

            _metadata = effectiveMetadata;
            _dataSpace = dataSpace;
        }
        internal DbModificationCommandTree(MetadataWorkspace metadata, DataSpace dataSpace, DbExpressionBinding target)
            : base(metadata, dataSpace)
        {
            EntityUtil.CheckArgumentNull(target, "target");

            this._target = target;
        }
        internal DbDeleteCommandTree(MetadataWorkspace metadata, DataSpace dataSpace, DbExpressionBinding target, DbExpression predicate)
            : base(metadata, dataSpace, target)
        {
            Contract.Requires(predicate != null);

            _predicate = predicate;
        }
        /// <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;
        }
        internal DbModificationCommandTree(MetadataWorkspace metadata, DataSpace dataSpace, DbExpressionBinding target)
            : base(metadata, dataSpace)
        {
            Contract.Requires(target != null);

            _target = target;
        }
        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;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DbDeleteCommandTree"/> class.
        /// </summary>
        /// <param name="metadata">The model this command will operate on.</param>
        /// <param name="dataSpace">The data space.</param>
        /// <param name="target">The target table for the data manipulation language (DML) operation.</param>
        /// <param name="predicate">A predicate used to determine which members of the target collection should be deleted.</param>
        public DbDeleteCommandTree(MetadataWorkspace metadata, DataSpace dataSpace, DbExpressionBinding target, DbExpression predicate)
            : base(metadata, dataSpace, target)
        {
            DebugCheck.NotNull(predicate);

            _predicate = predicate;
        }
        /// <summary>
        ///     Creates the full database scan expression.
        /// </summary>
        /// <param name="workspace">
        ///     The workspace that contains the metadata of the database
        /// </param>
        /// <param name="entitySet">
        ///     The entity set that is being scanned.
        /// </param>
        /// <returns>
        ///     The DbCommandTree object.
        /// </returns>
        public static DbCommandTree CreateSelectAll(
            MetadataWorkspace workspace,
            EntitySet entitySet)
        {
            #if !EFOLD
            var scanExpression = DbExpressionBuilder.Scan(entitySet);

            return new DbQueryCommandTree(workspace, DataSpace.SSpace, scanExpression);
            #else
            var treeConstructor =
                typeof(DbQueryCommandTree)
                .GetConstructor(
                    BindingFlags.NonPublic | BindingFlags.Instance,
                    null,
                    new Type[] { typeof(MetadataWorkspace), typeof(DataSpace), typeof(DbExpression) },
                    null);

            var expressionBuilderType =
                typeof(DbExpression).Assembly.GetType(
                    "System.Data.Common.CommandTrees.ExpressionBuilder.DbExpressionBuilder");

            var scanExpression = expressionBuilderType
                .GetMethod("Scan")
                .Invoke(null, new object[] { entitySet });

            var tree =
                treeConstructor.Invoke(
                    new object[] { workspace, DataSpace.SSpace, scanExpression });

            return tree as DbCommandTree;
            #endif
        }
Beispiel #14
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);
            }
        }
        /// <summary>
        /// Initializes a new command tree with a given metadata workspace.
        /// </summary>
        /// <param name="metadata">The metadata workspace against which the command tree should operate.</param>
        /// <param name="dataSpace">The logical 'space' that metadata in the expressions used in this command tree must belong to.</param>
        internal DbCommandTree(MetadataWorkspace metadata, DataSpace dataSpace)
        {
            // Ensure the metadata workspace is non-null
            EntityUtil.CheckArgumentNull(metadata, "metadata");

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

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

            this._metadata = effectiveMetadata;
            this._dataSpace = dataSpace;
        }
        internal DbModificationCommandTree(MetadataWorkspace metadata, DataSpace dataSpace, DbExpressionBinding target)
            : base(metadata, dataSpace)
        {
            DebugCheck.NotNull(target);

            _target = target;
        }
        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);
        }
 private CodeFirstCachedMetadataWorkspace(MetadataWorkspace metadataWorkspace, 
     IEnumerable<Assembly> assemblies, DbProviderInfo providerInfo, string defaultContainerName)
 {
     _metadataWorkspace = metadataWorkspace;
     _assemblies = assemblies;
     _providerInfo = providerInfo;
     _defaultContainerName = defaultContainerName;
 }
Beispiel #19
0
        /// <summary>
        /// Creates a new instance of perspective class so that query can work
        /// ignorant of all spaces
        /// </summary>
        /// <param name="metadataWorkspace">runtime metadata container</param>
        /// <param name="targetDataspace">target dataspace for the perspective</param>
        internal Perspective(MetadataWorkspace metadataWorkspace,
                             DataSpace targetDataspace)
        {
            EntityUtil.CheckArgumentNull(metadataWorkspace, "metadataWorkspace");

            m_metadataWorkspace = metadataWorkspace;
            m_targetDataspace = targetDataspace;
        }
 private IEnumerable<KeyValuePair<Shaper<RecordState>, CoordinatorFactory<RecordState>>> GetNextResultShaperInfo(
     DbDataReader storeDataReader, MetadataWorkspace workspace, IEnumerable<ColumnMap> nextResultColumnMaps)
 {
     foreach (var nextResultColumnMap in nextResultColumnMaps)
     {
         yield return CreateShaperInfo(storeDataReader, nextResultColumnMap, workspace);
     }
 }
        /// <summary>
        ///     Initialize Metadata for an AssociationSet
        /// </summary>
        internal AssociationSetMetadata(Set<EntitySet> affectedTables, AssociationSet associationSet, MetadataWorkspace workspace)
        {
            // If there is only 1 table, there can be no ambiguity about the "destination" of a relationship, so such
            // sets are not typically required.
            var isRequired = 1 < affectedTables.Count;

            // determine the ends of the relationship
            var ends = associationSet.AssociationSetEnds;

            // find collocated entities
            foreach (var table in affectedTables)
            {
                // Find extents influencing the table
                var influencingExtents = MetadataHelper.GetInfluencingEntitySetsForTable(table, workspace);

                foreach (var influencingExtent in influencingExtents)
                {
                    foreach (var end in ends)
                    {
                        // If the extent is an end of the relationship and we haven't already added it to the
                        // required set...
                        if (end.EntitySet.EdmEquals(influencingExtent))
                        {
                            if (isRequired)
                            {
                                AddEnd(ref RequiredEnds, end.CorrespondingAssociationEndMember);
                            }
                            else if (null == RequiredEnds
                                     || !RequiredEnds.Contains(end.CorrespondingAssociationEndMember))
                            {
                                AddEnd(ref OptionalEnds, end.CorrespondingAssociationEndMember);
                            }
                        }
                    }
                }
            }

            // fix Required and Optional sets
            FixSet(ref RequiredEnds);
            FixSet(ref OptionalEnds);

            // for associations with referential constraints, the principal end is always interesting
            // since its key values may take precedence over the key values of the dependent end
            foreach (var constraint in associationSet.ElementType.ReferentialConstraints)
            {
                // FromRole is the principal end in the referential constraint
                var principalEnd = (AssociationEndMember)constraint.FromRole;

                if (!RequiredEnds.Contains(principalEnd)
                    &&
                    !OptionalEnds.Contains(principalEnd))
                {
                    AddEnd(ref IncludedValueEnds, principalEnd);
                }
            }

            FixSet(ref IncludedValueEnds);
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="EntityTableDataLoader" /> class.
 /// </summary>
 /// <param name="connection"> The connection towards the database. </param>
 /// <param name="table"> The metadata of the table. </param>
 public EntityTableDataLoader(EntityConnection connection, TableDescription table)
     : base(table)
 {
     this.connection = connection;
     this.workspace = connection.GetMetadataWorkspace();
     this.entitySet = MetadataWorkspaceHelper
         .GetEntityContainer(this.workspace)
         .GetEntitySetByName(table.Name, true);
 }
        /// <summary>
        /// Creates a new instance of perspective class so that query can work
        /// ignorant of all spaces
        /// </summary>
        /// <param name="metadataWorkspace">runtime metadata container</param>
        /// <param name="targetDataspace">target dataspace for the perspective</param>
        internal Perspective(
            MetadataWorkspace metadataWorkspace,
            DataSpace targetDataspace)
        {
            //Contract.Requires(metadataWorkspace != null);

            m_metadataWorkspace = metadataWorkspace;
            m_targetDataspace = targetDataspace;
        }
Beispiel #24
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);
        }
        internal DbInsertCommandTree(MetadataWorkspace metadata, DataSpace dataSpace, DbExpressionBinding target, ReadOnlyModificationClauses setClauses, DbExpression returning)
            : base(metadata, dataSpace, target)
        {
            EntityUtil.CheckArgumentNull(setClauses, "setClauses");
            // returning may be null

            this._setClauses = setClauses;
            this._returning = returning;
        }
Beispiel #26
0
        // <summary>
        // Creates a new instance of perspective class so that query can work
        // ignorant of all spaces
        // </summary>
        // <param name="metadataWorkspace"> runtime metadata container </param>
        // <param name="targetDataspace"> target dataspace for the perspective </param>
        internal Perspective(
            MetadataWorkspace metadataWorkspace,
            DataSpace targetDataspace)
        {
            DebugCheck.NotNull(metadataWorkspace);

            _metadataWorkspace = metadataWorkspace;
            _targetDataspace = targetDataspace;
        }
        internal RelPropertyHelper(MetadataWorkspace ws, HashSet<RelProperty> interestingRelProperties)
        {
            _relPropertyMap = new Dictionary<EntityTypeBase, List<RelProperty>>();
            _interestingRelProperties = interestingRelProperties;

            foreach (var relationshipType in ws.GetItems<RelationshipType>(DataSpace.CSpace))
            {
                ProcessRelationship(relationshipType);
            }
        }
 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());            
 }
        public DbMapping(DbContext context)
        {
            _context = context;

              var objectContext = ((IObjectContextAdapter)context).ObjectContext;
              _metadataWorkspace = objectContext.MetadataWorkspace;

              _codeFirstEntityContainer = _metadataWorkspace.GetEntityContainer("CodeFirstDatabase", DataSpace.SSpace);

              MapDb();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DbInsertCommandTree"/> class.
        /// </summary>
        /// <param name="metadata">The model this command will operate on.</param>
        /// <param name="dataSpace">The data space.</param>
        /// <param name="target">The target table for the data manipulation language (DML) operation.</param>
        /// <param name="setClauses">The list of insert set clauses that define the insert operation. .</param>
        /// <param name="returning">A <see cref="DbExpression"/> that specifies a projection of results to be returned, based on the modified rows.</param>
        public DbInsertCommandTree(
            MetadataWorkspace metadata, DataSpace dataSpace, DbExpressionBinding target, ReadOnlyModificationClauses setClauses,
            DbExpression returning)
            : base(metadata, dataSpace, target)
        {
            DebugCheck.NotNull(setClauses);
            // returning may be null

            _setClauses = setClauses;
            _returning = returning;
        }
        internal static EdmType GetAndCheckFunctionImportReturnType <TElement>(
            EdmFunction functionImport,
            int resultSetIndex,
            MetadataWorkspace workspace)
        {
            EdmType returnType;

            if (!MetadataHelper.TryGetFunctionImportReturnType <EdmType>(functionImport, resultSetIndex, out returnType))
            {
                throw EntityUtil.ExecuteFunctionCalledWithNonReaderFunction(functionImport);
            }
            MetadataHelper.CheckFunctionImportReturnType <TElement>(returnType, workspace);
            return(returnType);
        }
Beispiel #32
0
        private MetadataWorkspace CheckRetrieveMetadata(Type t)
        {
            MetadataWorkspace ret;

            lock (this.metadatas)
            {
                if (!this.metadatas.TryGetValue(t, out ret))
                {
                    ret = new MetadataWorkspace(this.GenerateEntityMetadataPaths(t), new Assembly[] { t.Assembly });
                    this.metadatas.Add(t, ret);
                }
            }
            return(ret);
        }
Beispiel #33
0
        public static IDictionary <string, PropertyInfo> GetTableColumns(this MetadataWorkspace metadata, Type entityType)
        {
            var items             = metadata.GetItems(DataSpace.CSSpace);
            var storageEntityType = metadata.GetItems(DataSpace.SSpace)
                                    .Where(x => x.BuiltInTypeKind == BuiltInTypeKind.EntityType).OfType <EntityType>()
                                    .Single(x => x.Name == entityType.Name);

            var columnNames = storageEntityType.Properties.ToDictionary(x => x.Name,
                                                                        y => y.MetadataProperties.FirstOrDefault(x => x.Name == "PreferredName")?.Value as string ?? y.Name);

            return(storageEntityType.Properties.Select((elm, index) =>
                                                       new { elm.Name, Property = entityType.GetProperty(columnNames[elm.Name]) })
                   .ToDictionary(x => x.Name, x => x.Property));
        }
Beispiel #34
0
        public bool ContainsQuery(MetadataWorkspace workspace, string sql)
        {
            Guard.NotNull(workspace, nameof(workspace));
            Guard.NotEmpty(sql, nameof(sql));

            HashSet <string> queries;

            if (_queries.TryGetValue(workspace, out queries))
            {
                return(queries.Contains(sql));
            }

            return(false);
        }
        private static ModelMetadata GenerateModelMetadata(MetadataWorkspace ws)
        {
            var entityTypes = ws.GetItems <EntityType>(DataSpace.CSpace);

            var types       = entityTypes.Select(x => x.GetClrType());
            var constraints = entityTypes
                              .SelectMany(et => et.NavigationProperties)
                              .GroupBy(np => np.RelationshipType)
                              .Select(r => r.ToList())
                              .Where(r => r.Count == 2)
                              .SelectMany(r => GetConstraints(r[0], r[1]));

            return(new ModelMetadata(types, constraints));
        }
Beispiel #36
0
        internal ApiModelBuilder(string contextName, MetadataWorkspace dbMetadata)
        {
            this.contextName = contextName;
            this.dbMetadata  = dbMetadata;

            ObjectItemCollection objectItemCollection =
                (ObjectItemCollection)dbMetadata.GetItemCollection(DataSpace.OSpace);

            this.dbEntityTypes = dbMetadata.GetItems <EntityType>(DataSpace.OSpace).ToDictionary(
                et => objectItemCollection.GetClrType(et));

            this.entityTypeConfigs  = new Dictionary <Type, ApiEntityTypeConfiguration>();
            this.ignoredEntityTypes = null;
        }
            public void Registering_o_space_does_not_cause_oc_mapping_to_be_registered_if_c_space_is_not_registered()
            {
                var objectItemCollection = new ObjectItemCollection();

                var workspace = new MetadataWorkspace();

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

                Assert.Same(objectItemCollection, workspace.GetItemCollection(DataSpace.OSpace));
                ItemCollection _;
                Assert.False(workspace.TryGetItemCollection(DataSpace.OCSpace, out _));
            }
        internal void SetDefaultContainer(string defaultContainerName)
        {
            EntityContainer container = null;

            if (!String.IsNullOrEmpty(defaultContainerName))
            {
                if (!MetadataWorkspace.TryGetEntityContainer(defaultContainerName, DataSpace.CSpace, out container))
                {
                    throw new ArgumentException(
                              Strings.ObjectContext_InvalidDefaultContainerName(defaultContainerName), "defaultContainerName");
                }
            }
            _defaultContainer = container;
        }
Beispiel #39
0
        private KeyValuePair <Shaper <RecordState>, CoordinatorFactory <RecordState> > CreateShaperInfo(
            DbDataReader storeDataReader, ColumnMap columnMap, MetadataWorkspace workspace)
        {
            DebugCheck.NotNull(storeDataReader);
            DebugCheck.NotNull(columnMap);
            DebugCheck.NotNull(workspace);

            var shaperFactory = _translator.TranslateColumnMap <RecordState>(columnMap, workspace, null, MergeOption.NoTracking, streaming: true, valueLayer: true);
            var recordShaper  = shaperFactory.Create(
                storeDataReader, null, workspace, MergeOption.NoTracking, readerOwned: true, streaming: true);

            return(new KeyValuePair <Shaper <RecordState>, CoordinatorFactory <RecordState> >(
                       recordShaper, recordShaper.RootCoordinator.TypedCoordinatorFactory));
        }
Beispiel #40
0
        internal Shaper(
            DbDataReader reader, ObjectContext context, MetadataWorkspace workspace, MergeOption mergeOption,
            int stateCount, bool streaming)
        {
            Debug.Assert(context == null || workspace == context.MetadataWorkspace, "workspace must match context's workspace");

            Reader         = reader;
            MergeOption    = mergeOption;
            State          = new object[stateCount];
            Context        = context;
            Workspace      = workspace;
            _spatialReader = new Lazy <DbSpatialDataReader>(CreateSpatialDataReader);
            Streaming      = streaming;
        }
            public void ImplicitLoadAssemblyForType_checks_only_calling_assembly_for_views_if_type_assembly_filtered_and_no_schema_attribute()
            {
                var mockCache = new Mock <IViewAssemblyCache>();
                var workspace = new MetadataWorkspace(
                    () => new EdmItemCollection(Enumerable.Empty <XmlReader>()),
                    () => null,
                    () => null,
                    () => new ObjectItemCollection(mockCache.Object));

                workspace.ImplicitLoadAssemblyForType(typeof(object), typeof(FactAttribute).Assembly);

                mockCache.Verify(m => m.CheckAssembly(typeof(object).Assembly, It.IsAny <bool>()), Times.Never());
                mockCache.Verify(m => m.CheckAssembly(typeof(FactAttribute).Assembly, false), Times.Once());
            }
Beispiel #42
0
        private static ObjectContext GetObjectContext(string connectionString)
        {
            // You can use the metadata portion of the connection string the the designer added to your config for the paths
            var paths = new[] {
                "res://*/Northwind.csdl",
                "res://*/Northwind.ssdl",
                "res://*/Northwind.msl"
            };

            var workspace  = new MetadataWorkspace(paths, new[] { typeof(NorthwindEntities).Assembly });
            var connection = new EntityConnection(workspace, new SqlConnection(connectionString));

            return(new ObjectContext(connection));
        }
        public static string[] GetKeyNames(this DbContext context, Type entityType)
        {
            MetadataWorkspace metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace;

            // Get the mapping between CLR types and metadata OSpace
            ObjectItemCollection objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace));

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

            return(entityMetadata.KeyProperties.Select(p => p.Name).ToArray());
        }
Beispiel #44
0
        internal static object GetSpatialValue(
            MetadataWorkspace workspace,
            DbDataReader reader,
            TypeUsage columnType,
            int columnOrdinal)
        {
            DbSpatialDataReader spatialDataReader = SpatialHelpers.CreateSpatialDataReader(workspace, reader);

            if (Helper.IsGeographicType((PrimitiveType)columnType.EdmType))
            {
                return((object)spatialDataReader.GetGeography(columnOrdinal));
            }
            return((object)spatialDataReader.GetGeometry(columnOrdinal));
        }
Beispiel #45
0
        /// <summary>A MetadataWorkspace extension method that gets entity type by type.</summary>
        /// <param name="metadataWorkspace">The metadataWorkspace to act on.</param>
        /// <param name="entityType">Type of the entity.</param>
        /// <returns>The entity type by type.</returns>
        /// not support class in generic class
        internal static EntityType GetEntityTypeByType(this MetadataWorkspace metadataWorkspace, Type entityType)
        {
            string name   = entityType.FullName.Replace("+", ".");
            var    lenght = name.IndexOf("`");

            if (lenght != -1)
            {
                name = name.Substring(0, lenght);
            }

            return(metadataWorkspace
                   .GetItems <EntityType>(DataSpace.OSpace)
                   .SingleOrDefault(p => p.FullName == name));
        }
Beispiel #46
0
        internal static object GetSpatialValue(MetadataWorkspace workspace, DbDataReader reader, TypeUsage columnType, int columnOrdinal)
        {
            Debug.Assert(Helper.IsSpatialType(columnType));
            var spatialReader = CreateSpatialDataReader(workspace, reader);

            if (Helper.IsGeographicType((PrimitiveType)columnType.EdmType))
            {
                return(spatialReader.GetGeography(columnOrdinal));
            }
            else
            {
                return(spatialReader.GetGeometry(columnOrdinal));
            }
        }
Beispiel #47
0
        /// <summary>
        ///     Initializes a new command tree with a given metadata workspace.
        /// </summary>
        /// <param name="metadata"> The metadata workspace against which the command tree should operate. </param>
        /// <param name="dataSpace"> The logical 'space' that metadata in the expressions used in this command tree must belong to. </param>
        internal DbCommandTree(MetadataWorkspace metadata, DataSpace dataSpace)
        {
            // Ensure the metadata workspace is non-null
            DebugCheck.NotNull(metadata);

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

            _metadata  = metadata;
            _dataSpace = dataSpace;
        }
Beispiel #48
0
        private MetadataWorkspace LoadFromFiles()
        {
            var sw = Stopwatch.StartNew();

            var modelFilesPath = EntityFrameworkMapping.ModelFiles.Select(fileName => Path.Combine(_rhetosAppOptions.AssetsFolder, fileName)).ToList();

            SetProviderManifestTokenIfNeeded(sw, modelFilesPath);

            var metadataWorkspace = new MetadataWorkspace(modelFilesPath, Array.Empty <Assembly>());

            _performanceLogger.Write(sw, "Load EDM files.");

            return(metadataWorkspace);
        }
Beispiel #49
0
 internal DbExpressionValidator(MetadataWorkspace metadata, DataSpace expectedDataSpace)
     : base(metadata)
 {
     requiredSpace         = expectedDataSpace;
     allowedFunctionSpaces = new[] { DataSpace.CSpace, DataSpace.SSpace };
     if (expectedDataSpace == DataSpace.SSpace)
     {
         allowedMetadataSpaces = new[] { DataSpace.SSpace, DataSpace.CSpace };
     }
     else
     {
         allowedMetadataSpaces = new[] { DataSpace.CSpace };
     }
 }
Beispiel #50
0
        internal static DbSpatialDataReader CreateSpatialDataReader(MetadataWorkspace workspace, DbDataReader reader)
        {
            StoreItemCollection storeItemCollection = (StoreItemCollection)workspace.GetItemCollection(DataSpace.SSpace);
            DbProviderFactory   providerFactory     = storeItemCollection.StoreProviderFactory;

            Debug.Assert(providerFactory != null, "GetProviderSpatialServices requires provider factory to have been initialized");

            DbProviderServices  providerServices = DbProviderServices.GetProviderServices(providerFactory);
            DbSpatialDataReader result           = providerServices.GetSpatialDataReader(reader, storeItemCollection.StoreProviderManifestToken);

            Debug.Assert(result != null, "DbProviderServices did not throw ProviderIncompatibleException for null IDbSpatialDataReader");

            return(result);
        }
Beispiel #51
0
        public Repository(DbContext context, ConnectionFactory.ConnectionMethod conn, string connectionString = null,
                          bool killConnectionOnCtxDispose = false, DbConnection changeLogConnectionContext = null)
        {
            _ChangeLogQueue     = new List <ChangeLog_Entry>();
            ContextChangesQueue = new List <ContextChange_DTO>();

            KillConnectionOnDispose = killConnectionOnCtxDispose;

            ctx = context;
            ConnectionString = ctx.Database.Connection.ConnectionString;
            Workspace        = ((IObjectContextAdapter)ctx).ObjectContext.MetadataWorkspace;

            LoadLogger(conn, connectionString, killConnectionOnCtxDispose, changeLogConnectionContext);
        }
Beispiel #52
0
        private static string GetTableName(Type type, DbContext context)
        {
            MetadataWorkspace metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace;

            // Get the part of the model that contains info about the actual CLR types
            ObjectItemCollection objectItemCollection = (ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace);

            // Get the entity type from the model that maps to the CLR type
            EntityType entityType = metadata
                                    .GetItems <EntityType>(DataSpace.OSpace)
                                    .FirstOrDefault(e => objectItemCollection.GetClrType(e) == type);

            if (entityType == null)
            {
                return(null);
            }

            // Get the entity set that uses this entity type
            EntitySet entitySet = metadata
                                  .GetItems <EntityContainer>(DataSpace.CSpace)
                                  .Single()
                                  .EntitySets
                                  .FirstOrDefault(s => s.ElementType.Name == entityType.Name);

            if (entitySet == null)
            {
                return(null);
            }

            // Find the mapping between conceptual and storage model for this entity set
            EntitySetMapping mapping = metadata.GetItems <EntityContainerMapping>(DataSpace.CSSpace)
                                       .Single()
                                       .EntitySetMappings
                                       .Single(s => s.EntitySet == entitySet);

            if (mapping == null)
            {
                return(null);
            }

            // Find the storage entity set (table) that the entity is mapped
            EntitySet table = mapping
                              .EntityTypeMappings.Single()
                              .Fragments.Single()
                              .StoreEntitySet;

            // Return the table name from the storage entity set
            return(string.Format("[{0}].[{1}]", table.Schema, (string)table.MetadataProperties["Table"].Value ?? table.Name));
        }
        private MetadataWorkspace CreateDrawingsAndSubdrawingsXmlMetadata()
        {
            EntityType drawingsType = new EntityType();

            drawingsType.Name = "Drawings";
            drawingsType.PrimaryKey.Add(new KeyMember("Id", 0));
            drawingsType.Properties["Id"]       = DataType.Integer;
            drawingsType.Properties["Title"]    = DataType.String;
            drawingsType.Properties["Width"]    = DataType.Integer;
            drawingsType.Properties["Height"]   = DataType.Integer;
            drawingsType.Properties["BgColour"] = DataType.Integer;

            EntityType subDrawingsType = new EntityType();

            subDrawingsType.Name = "SubDrawings";
            subDrawingsType.PrimaryKey.Add(new KeyMember("MainDrawing", 0));
            subDrawingsType.PrimaryKey.Add(new KeyMember("SubDrawing", 1));
            subDrawingsType.PrimaryKey.Add(new KeyMember("X", 2));
            subDrawingsType.PrimaryKey.Add(new KeyMember("Y", 3));
            subDrawingsType.PrimaryKey.Add(new KeyMember("Z", 4));
            subDrawingsType.Properties["MainDrawing"] = DataType.Integer;
            subDrawingsType.Properties["SubDrawing"]  = DataType.Integer;
            subDrawingsType.Properties["X"]           = DataType.Integer;
            subDrawingsType.Properties["Y"]           = DataType.Integer;
            subDrawingsType.Properties["Z"]           = DataType.Integer;

            Association subdrawingsMainToDrawings = new Association();

            subdrawingsMainToDrawings.Name      = "SubDrawings_Drawings_Main";
            subdrawingsMainToDrawings.Principal = "Drawings";
            subdrawingsMainToDrawings.Dependent = "SubDrawings";
            subdrawingsMainToDrawings.PropertyMappings["Id"] = "MainDrawing";

            Association subdrawingsSubsToDrawings = new Association();

            subdrawingsSubsToDrawings.Name      = "SubDrawings_Drawings_Sub";
            subdrawingsSubsToDrawings.Principal = "Drawings";
            subdrawingsSubsToDrawings.Dependent = "SubDrawings";
            subdrawingsSubsToDrawings.PropertyMappings["Id"] = "SubDrawing";

            MetadataWorkspace xmlMetadataWorkspace = new MetadataWorkspace();

            xmlMetadataWorkspace.EntityTypes.Add(drawingsType);
            xmlMetadataWorkspace.EntityTypes.Add(subDrawingsType);
            xmlMetadataWorkspace.Associations.Add(subdrawingsMainToDrawings);
            xmlMetadataWorkspace.Associations.Add(subdrawingsSubsToDrawings);

            return(xmlMetadataWorkspace);
        }
        /// <summary>

        /// Generate an Entity set for TEntity

        /// so that we can inspect the metadata

        /// </summary>

        /// <typeparam name="TEntity"></typeparam>

        /// <param name="dbCtx"></param>

        /// <returns></returns>

        private static EntitySet GetMetaDataEntitySet <TEntity>(DbContext dbCtx)

        {
            Type entityType = typeof(TEntity);

            string entityName = entityType.Name;

            MetadataWorkspace metaDataWS = ((IObjectContextAdapter)dbCtx).ObjectContext.MetadataWorkspace;



            //IEnumerable<EntitySet> entitySets;

            var entitySets = metaDataWS.GetItemCollection(DataSpace.SSpace)

                             .GetItems <EntityContainer>()

                             .Single()

                             .BaseEntitySets

                             .OfType <EntitySet>()

                             .Where(entitySet => !entitySet.MetadataProperties.Contains("Type")

                                    || entitySet.MetadataProperties["Type"].ToString() == "Tables");



            List <EntitySet> provisionedTables = entitySets.ToList();

            EntitySet returnValue = provisionedTables.FirstOrDefault(t => t.Name == entityName);

            //When an Entity inherits a base class, the corresponding

            //table is sometimes named for the base class

            while (null == returnValue && null != entityType)

            {
                entityType = entityType.BaseType;

                entityName = entityType.Name;

                returnValue = provisionedTables.FirstOrDefault(t => t.Name == entityName);
            }

            return(returnValue);
        }
    public static EntityConnection Create(List <ColumnsToRemove> tablesAndColumns, string connString)
    {
        var modelNameRegex   = new Regex(@".*metadata=res:\/\/\*\/([a-zA-Z.]*).csdl|.*");
        var model            = modelNameRegex.Matches(connString).Cast <Match>().SelectMany(o => o.Groups.Cast <Group>().Skip(1).Where(oo => oo.Value != "")).Select(o => o.Value).First();
        var conceptualReader = XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream(model + ".csdl"));
        var mappingReader    = XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream(model + ".msl"));
        var storageReader    = XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream(model + ".ssdl"));
        var conceptualXml    = XElement.Load(conceptualReader);
        var mappingXml       = XElement.Load(mappingReader);
        var storageXml       = XElement.Load(storageReader);

        foreach (var entitySet in new[] { storageXml, conceptualXml }.SelectMany(xml => xml.Elements()))
        {
            if (entitySet.Attribute("Name").Value == "ModelStoreContainer")
            {
                foreach (var entityContainerEntitySet in entitySet.Elements())
                {
                    RemoveNodes(entityContainerEntitySet, tablesAndColumns);
                }
            }
            RemoveNodes(entitySet, tablesAndColumns);
        }
        foreach (var entitySet in mappingXml.Elements().ElementAt(0).Elements())
        {
            if (entitySet.Name.LocalName == "EntitySetMapping")
            {
                foreach (var entityContainerEntitySet in entitySet.Elements().First().Elements())
                {
                    RemoveNodes(entityContainerEntitySet, tablesAndColumns);
                }
            }
            RemoveNodes(entitySet, tablesAndColumns);
        }
        var storageCollection    = new StoreItemCollection(new [] { storageXml.CreateReader() });
        var conceptualCollection = new EdmItemCollection(new[] { conceptualXml.CreateReader() });
        var mappingCollection    = new StorageMappingItemCollection(conceptualCollection, storageCollection, new[] { mappingXml.CreateReader() });
        var workspace            = new MetadataWorkspace();

        workspace.RegisterItemCollection(conceptualCollection);
        workspace.RegisterItemCollection(storageCollection);
        workspace.RegisterItemCollection(mappingCollection);
        var connectionData = new EntityConnectionStringBuilder(connString);
        var connection     = DbProviderFactories
                             .GetFactory(connectionData.Provider)
                             .CreateConnection();

        connection.ConnectionString = connectionData.ProviderConnectionString;
        return(new EntityConnection(workspace, connection));
    }
Beispiel #56
0
        public void Can_load_entity_with_property_of_enum_type_from_different_assembly()
        {
            const bool isPOCO = true;

            var enumTypeCsdl = XDocument.Parse(
                @"<Schema xmlns=""http://schemas.microsoft.com/ado/2009/11/edm"" Namespace=""EnumModel"">
  <EnumType Name=""Enum"" IsFlags=""false"" />
</Schema>");

            var entityTypeCsdl = XDocument.Parse(
                @"<Schema xmlns=""http://schemas.microsoft.com/ado/2009/11/edm"" Namespace=""EnumModel"">
  <EntityContainer Name=""EnumModelContainer"">
    <EntitySet Name=""Entity"" EntityType=""EnumModel.Entity"" />
  </EntityContainer>
  <EntityType Name=""Entity"">
    <Key>
      <PropertyRef Name=""Id"" />
    </Key>
    <Property Name=""Id"" Nullable=""false"" Type=""Int32"" />
    <Property Name=""EnumProperty"" Nullable=""false"" Type=""EnumModel.Enum"" />
  </EntityType>
</Schema>");

            var assemblyWithEnumType   = BuildAssembly(isPOCO, enumTypeCsdl);
            var assemblyWithEntityType = BuildAssembly(isPOCO, entityTypeCsdl);

            EdmItemCollection edmItemCollection;

            var workspace = new MetadataWorkspace();

            using (var enumTypeReader = enumTypeCsdl.CreateReader())
                using (var entityTypeReader = entityTypeCsdl.CreateReader())
                {
                    edmItemCollection =
                        new EdmItemCollection(
                            new XmlReader[] { enumTypeReader, entityTypeReader });
                }
            workspace.RegisterItemCollection(edmItemCollection);

            var objectItemCollection = new ObjectItemCollection();

            objectItemCollection.LoadFromAssembly(assemblyWithEnumType, edmItemCollection);
            objectItemCollection.LoadFromAssembly(assemblyWithEntityType, edmItemCollection);
            workspace.RegisterItemCollection(objectItemCollection);

            Assert.Equal(
                "EnumModel.Entity:EnumModel.Entity",
                workspace.GetMap("EnumModel.Entity", DataSpace.OSpace, DataSpace.OCSpace).Identity);
        }
Beispiel #57
0
    public EntityObject NewEntityFromOrig(MetadataWorkspace mdw)
    {
        var newEntity    = Activator.CreateInstance(_detachedEntity.GetType());
        var newEntityObj = (EntityObject)newEntity;

        newEntityObj.EntityKey = _entityKey;
        //use metadata and Reflection to populate entity
        var etype = newEntity.GetType();

        foreach (var p in etype.GetProperties())
        {
            //find the correct property in origvalues
            object origPropertyValue;
            if (_origValues.TryGetValue(p.Name, out origPropertyValue))
            {
                p.SetValue(newEntity, origPropertyValue, null);
            }
            else
            {
                if (p.PropertyType.Name.StartsWith("EntityReference"))
                {
                    //there is a "'1" in the propertytype.name
                    var lastReference = p.Name.LastIndexOf("Reference");
                    var entName       = p.Name.Remove(lastReference);
                    var entitySetName = mdw.GetEntitySetName(entName);
                    var eref          = (EntityReference)(p.GetValue(newEntity, null));

                    //be sure that a deleted relationship is added before an added relationship
                    foreach (var rel in _relationships)
                    {
                        if (rel.CurrentEndA.EntitySetName == entitySetName)
                        {
                            //this is the entitykey we want,
                            //but we need to set entityreference.entitykey
                            eref.EntityKey = rel.CurrentEndA;
                        }
                        else if (rel.CurrentEndB.EntitySetName == entitySetName)
                        {
                            eref.EntityKey = rel.CurrentEndB;
                        }
                    }
                    //find entitykey
                }
            }
        }
        //after this, the calling code needs to attach to context,
        // then apply property changes using the detached entity
        return((EntityObject)newEntity);
    }
        private static MetadataWorkspace GetProviderSchemaMetadataWorkspace(
            IDbDependencyResolver resolver, string providerInvariantName, SystemDataCommon.DbConnection providerConnection,
            Version targetSchemaVersion)
        {
            Debug.Assert(resolver != null, "resolver != null");
            Debug.Assert(!string.IsNullOrWhiteSpace(providerInvariantName), "providerInvarianName cannot be null or empty");
            Debug.Assert(providerConnection != null, "providerConnection != null");
            Debug.Assert(EntityFrameworkVersion.IsValidVersion(targetSchemaVersion), "invalid targetSchemaVersion");

            string csdlName;
            string ssdlName;
            string mslName;

            if (targetSchemaVersion >= EntityFrameworkVersion.Version3)
            {
                csdlName = DbProviderManifest.ConceptualSchemaDefinitionVersion3;
                ssdlName = DbProviderManifest.StoreSchemaDefinitionVersion3;
                mslName  = DbProviderManifest.StoreSchemaMappingVersion3;
            }
            else
            {
                csdlName = DbProviderManifest.ConceptualSchemaDefinition;
                ssdlName = DbProviderManifest.StoreSchemaDefinition;
                mslName  = DbProviderManifest.StoreSchemaMapping;
            }

            var providerServices = resolver.GetService <DbProviderServices>(providerInvariantName);

            Debug.Assert(providerServices != null, "Trying to get unregistered provider.");

            var providerManifest =
                providerServices.GetProviderManifest(
                    providerServices.GetProviderManifestToken(providerConnection));

            var edmItemCollection     = LoadEdmItemCollection(csdlName);
            var storeItemCollection   = LoadStoreItemCollection(providerManifest, ssdlName);
            var mappingItemCollection = LoadMappingItemCollection(providerManifest, mslName, edmItemCollection, storeItemCollection);
            var workspace             = new MetadataWorkspace(
                () => edmItemCollection,
                () => storeItemCollection,
                () => mappingItemCollection);

            // TODO: there is currently no public surface to do this (workitem 606 on codeplex)
            //// make the views generate here so we can wrap the provider schema problems
            //// in a ProviderIncompatibleException
            //ForceViewGeneration(workspace);

            return(workspace);
        }
Beispiel #59
0
        private static XDocument UpdateCSpaceOSpaceMappingCore(XDocument xDoc, MetadataWorkspace metadataWs)
        {
            var cspaceTypes = metadataWs.GetItems <System.Data.Entity.Core.Metadata.Edm.StructuralType>(DataSpace.CSpace);
            var tpls        = cspaceTypes
                              .Where(st => !(st is AssociationType))
                              .Select(st => {
                var ost = metadataWs.GetObjectSpaceType(st);
                return(new[] { st.FullName, ost.FullName });
            })
                              .ToList();
            var ocMapping = JsonConvert.SerializeObject(tpls);

            xDoc.Root.SetAttributeValue("CSpaceOSpaceMapping", ocMapping);
            return(xDoc);
        }
Beispiel #60
0
        public virtual DbDataReader Create(
            DbDataReader storeDataReader, ColumnMap columnMap, MetadataWorkspace workspace, IEnumerable <ColumnMap> nextResultColumnMaps)
        {
            DebugCheck.NotNull(storeDataReader);
            DebugCheck.NotNull(columnMap);
            DebugCheck.NotNull(workspace);
            DebugCheck.NotNull(nextResultColumnMaps);

            var          shaperInfo = CreateShaperInfo(storeDataReader, columnMap, workspace);
            DbDataReader result     = new BridgeDataReader(
                shaperInfo.Key, shaperInfo.Value, /*depth:*/ 0,
                GetNextResultShaperInfo(storeDataReader, workspace, nextResultColumnMaps).GetEnumerator());

            return(result);
        }