Beispiel #1
0
 protected override void evaluateArguments(Arguments arguments, out List <ParameterValue> values, out bool partial,
                                           bool register)
 {
     values = parameters.GetArguments(arguments);
     memo.Evaluate(values);
     Parameters.SetArguments(values);
     partial = false;
 }
        /// <summary>
        /// Called to create a new wrapper outside of the normal materialization process.
        /// This method is typically used when a new entity is created outside the context and then is
        /// added or attached.  The materializer bypasses this method and calls wrapper constructors
        /// directory for performance reasons.
        /// This method does not check whether or not the wrapper already exists in the context.
        /// </summary>
        /// <param name="entity">The entity for which a wrapper will be created</param>
        /// <param name="key">The key associated with that entity, or null</param>
        /// <returns>The new wrapper instance</returns>
        internal static IEntityWrapper CreateNewWrapper(object entity, EntityKey key)
        {
            Debug.Assert(!(entity is IEntityWrapper), "Object is an IEntityWrapper instance instead of the raw entity.");
            if (entity == null)
            {
                return(NullEntityWrapper.NullWrapper);
            }
            // We used a cache of functions based on the actual type of entity that we need to wrap.
            // Creatung these functions is slow, but once they are created they are relatively fast.
            IEntityWrapper wrappedEntity = _delegateCache.Evaluate(entity.GetType())(entity);

            wrappedEntity.RelationshipManager.SetWrappedOwner(wrappedEntity, entity);
            // We cast to object here to avoid calling the overridden != operator on EntityKey.
            // This creates a very small perf gain, which is none-the-less significant for lean no-tracking cases.
            if ((object)key != null && (object)wrappedEntity.EntityKey == null)
            {
                wrappedEntity.EntityKey = key;
            }

            // If the entity is a proxy, set the wrapper to match
            EntityProxyTypeInfo proxyTypeInfo;

            if (EntityProxyFactory.TryGetProxyType(entity.GetType(), out proxyTypeInfo))
            {
                proxyTypeInfo.SetEntityWrapper(wrappedEntity);
            }

            return(wrappedEntity);
        }
Beispiel #3
0
        internal string GetRename(EdmType type, out IXmlLineInfo lineInfo)
        {
            DebugCheck.NotNull(type);

            Debug.Assert(type is StructuralType, "we can only rename structural type");

            var rename = _renameCache.Evaluate(type as StructuralType);

            lineInfo = rename.LineInfo;
            return(rename.ColumnName);
        }
        // <summary>
        // Generates function definition or returns a cached one.
        // Guarantees type match of declaration and generated parameters.
        // Guarantees return type match.
        // Throws internal error for functions without definition.
        // Passes thru exceptions occured during definition generation.
        // </summary>
        internal DbLambda GetGeneratedFunctionDefinition(EdmFunction function)
        {
            if (null == _getGeneratedFunctionDefinitionsMemoizer)
            {
                Interlocked.CompareExchange(
                    ref _getGeneratedFunctionDefinitionsMemoizer,
                    new Memoizer <EdmFunction, DbLambda>(GenerateFunctionDefinition, null),
                    null);
            }

            return(_getGeneratedFunctionDefinitionsMemoizer.Evaluate(function));
        }
Beispiel #5
0
        /// <summary>
        /// Given an InitializerMetadata instance, returns the canonical version of that instance.
        /// This allows us to avoid compiling materialization delegates repeatedly for the same
        /// pattern.
        /// </summary>
        internal InitializerMetadata GetCanonicalInitializerMetadata(InitializerMetadata metadata)
        {
            if (null == _getCanonicalInitializerMetadataMemoizer)
            {
                // We memoize the identity function because the first evaluation of the function establishes
                // the canonical 'reference' for the initializer metadata with a particular 'value'.
                Interlocked.CompareExchange(ref _getCanonicalInitializerMetadataMemoizer, new Memoizer <InitializerMetadata, InitializerMetadata>(
                                                m => m, EqualityComparer <InitializerMetadata> .Default), null);
            }

            // check if an equivalent has already been registered
            InitializerMetadata canonical = _getCanonicalInitializerMetadataMemoizer.Evaluate(metadata);

            return(canonical);
        }
        internal override bool ColumnValueMatchesCondition(object columnValue)
        {
            if (null == columnValue || Convert.IsDBNull(columnValue))
            {
                // only FunctionImportEntityTypeMappingConditionIsNull can match a null
                // column value
                return(false);
            }

            Type columnValueType = columnValue.GetType();

            // check if we've interpreted this column type yet
            object conditionValue = _convertedValues.Evaluate(columnValueType);

            return(ByValueEqualityComparer.Default.Equals(columnValue, conditionValue));
        }
Beispiel #7
0
        public MetadataArtifactLoader GetArtifactLoader(DbConnectionOptions effectiveConnectionOptions)
        {
            DebugCheck.NotNull(effectiveConnectionOptions);

            var paths = effectiveConnectionOptions[EntityConnectionStringBuilder.MetadataParameterName];

            if (!string.IsNullOrEmpty(paths))
            {
                var loaders = _artifactLoaderCache.Evaluate(paths);

                return(MetadataArtifactLoader.Create(
                           ShouldRecalculateMetadataArtifactLoader(loaders)
                        ? SplitPaths(paths)
                        : loaders));
            }

            return(MetadataArtifactLoader.Create(new List <MetadataArtifactLoader>()));
        }
Beispiel #8
0
        /// <summary>Returns all the items of the specified type from this item collection.</summary>
        /// <returns>
        ///     A collection of type <see cref="T:System.Collections.ObjectModel.ReadOnlyCollection`1" /> that contains all the items of the specified type.
        /// </returns>
        /// <typeparam name="T">The type returned by the method.</typeparam>
        public virtual ReadOnlyCollection <T> GetItems <T>() where T : GlobalItem
        {
            var currentValueForItemCache = _itemsCache;

            // initialize the memoizer, update the _itemCache and _itemCount
            if (_itemsCache == null ||
                _itemCount != Count)
            {
                var itemsCache =
                    new Memoizer <Type, ICollection>(InternalGetItems, null);
                Interlocked.CompareExchange(ref _itemsCache, itemsCache, currentValueForItemCache);

                _itemCount = Count;
            }

            Debug.Assert(_itemsCache != null, "check the initialization of the Memoizer");

            // use memoizer so that it won't create a new list every time this method get called
            var items       = _itemsCache.Evaluate(typeof(T));
            var returnItems = items as ReadOnlyCollection <T>;

            return(returnItems);
        }
Beispiel #9
0
 internal static XmlSchemaSet GetSchemaSet(SchemaDataModelOption dataModel)
 {
     return(_cachedSchemaSets.Evaluate(dataModel));
 }
 /// <summary>
 /// Get TypeReference for a bound generic framework class
 /// </summary>
 /// <param name="namespaceName">the namespace of the generic framework class</param>
 /// <param name="name">the name of the generic framework class</param>
 /// <param name="typeParameter">the type parameter for the framework class</param>
 /// <returns>TypeReference for the bound framework class</returns>
 private CodeTypeReference FrameworkGenericClass(string namespaceName, string name, CodeTypeReference typeParameter)
 {
     return(_fromStringGenericMemoizer.Evaluate(new KeyValuePair <string, CodeTypeReference>(namespaceName + "." + name, typeParameter)));
 }
 internal static bool ShouldFilterAssembly(Assembly assembly)
 {
     return(_filterAssemblyCacheByAssembly.Evaluate(assembly));
 }
Beispiel #12
0
 internal EdmFunction ConvertToCTypeFunction(EdmFunction sTypeFunction)
 {
     return(_cachedCTypeFunction.Evaluate(sTypeFunction));
 }
Beispiel #13
0
 internal OutputFromComputeCellGroups GetCellgroups(InputForComputingCellGroups args)
 {
     Debug.Assert(ReferenceEquals(this, args.ContainerMapping));
     return(m_memoizedCellGroupEvaluator.Evaluate(args));
 }
Beispiel #14
0
 /// <summary>
 /// Get TypeReference for a type represented by a namespace quailifed string,
 /// with optional global qualifier
 /// </summary>
 /// <param name="type">namespace qualified string</param>
 /// <param name="addGlobalQualifier">indicates whether the global qualifier should be added</param>
 /// <returns>the TypeReference</returns>
 public CodeTypeReference FromString(string type, bool addGlobalQualifier)
 {
     return(_fromStringMemoizer.Evaluate(new KeyValuePair <string, bool>(type, addGlobalQualifier)));
 }
Beispiel #15
0
 /// <summary>
 /// Get TypeReference for a bound generic framework class
 /// </summary>
 /// <param name="fullname">the fully qualified name of the generic framework class</param>
 /// <param name="typeParameter">the type parameter for the framework class</param>
 /// <returns>TypeReference for the bound framework class</returns>
 public CodeTypeReference FrameworkGenericClass(string fullname, CodeTypeReference typeParameter)
 {
     return(_fromStringGenericMemoizer.Evaluate(new KeyValuePair <string, CodeTypeReference>(fullname, typeParameter)));
 }
            /// <summary>
            /// Returns the update or query view for an Extent as a
            /// string.
            /// There are a series of steps that we go through for discovering a view for an extent.
            /// To start with we assume that we are working with Generated Views. To find out the
            /// generated view we go to the ObjectItemCollection and see if it is not-null. If the ObjectItemCollection
            /// is non-null, we get the view generation assemblies that it might have cached during the
            /// Object metadata discovery.If there are no view generation assemblies we switch to the
            /// runtime view generation strategy. If there are view generation assemblies, we get the list and
            /// go through them and see if there are any assemblies that are there from which we have not already loaded
            /// the views. We collect the views from assemblies that we have not already collected from earlier.
            /// If the ObjectItemCollection is null and we are in the view generation mode, that means that
            /// the query or update is issued from the Value layer and this is the first time view has been asked for.
            /// The compile time view gen for value layer queries will work for very simple scenarios.
            /// If the users wants to get the performance benefit, they should call MetadataWorkspace.LoadFromAssembly.
            /// At this point we go through the referenced assemblies of the entry assembly( this wont work for Asp.net
            /// or if the viewgen assembly was not referenced by the executing application).
            /// and try to see if there were any view gen assemblies. If there are, we collect the views for all extents.
            /// Once we have all the generated views gathered, we try to get the view for the extent passed in.
            /// If we find one we will return it. If we can't find one an exception will be thrown.
            /// If there were no view gen assemblies either in the ObjectItemCollection or in the list of referenced
            /// assemblies of calling assembly, we change the mode to runtime view generation and will continue to
            /// be in that mode for the rest of the lifetime of the mapping item collection.
            /// </summary>
            internal GeneratedView GetGeneratedView(EntitySetBase extent, MetadataWorkspace workspace, StorageMappingItemCollection storageMappingItemCollection)
            {
                //First check if we have collected a view from user-defined query views
                //Dont need to worry whether to generate Query view or update viw, because that is relative to the extent.
                GeneratedView view;

                if (TryGetUserDefinedQueryView(extent, out view))
                {
                    return(view);
                }

                //If this is a foreign key association, manufacture a view on the fly.
                if (extent.BuiltInTypeKind == BuiltInTypeKind.AssociationSet)
                {
                    AssociationSet aSet = (AssociationSet)extent;
                    if (aSet.ElementType.IsForeignKey)
                    {
                        if (m_config.IsViewTracing)
                        {
                            Helpers.StringTraceLine(String.Empty);
                            Helpers.StringTraceLine(String.Empty);
                            Helpers.FormatTraceLine("================= Generating FK Query View for: {0} =================", aSet.Name);
                            Helpers.StringTraceLine(String.Empty);
                            Helpers.StringTraceLine(String.Empty);
                        }

                        // Although we expose a collection of constraints in the API, there is only ever one constraint.
                        Debug.Assert(aSet.ElementType.ReferentialConstraints.Count == 1, "aSet.ElementType.ReferentialConstraints.Count == 1");
                        ReferentialConstraint rc = aSet.ElementType.ReferentialConstraints.Single();

                        EntitySet dependentSet = aSet.AssociationSetEnds[rc.ToRole.Name].EntitySet;
                        EntitySet principalSet = aSet.AssociationSetEnds[rc.FromRole.Name].EntitySet;

                        DbExpression qView = dependentSet.Scan();

                        // Introduce an OfType view if the dependent end is a subtype of the entity set
                        EntityType dependentType = MetadataHelper.GetEntityTypeForEnd((AssociationEndMember)rc.ToRole);
                        EntityType principalType = MetadataHelper.GetEntityTypeForEnd((AssociationEndMember)rc.FromRole);
                        if (dependentSet.ElementType.IsBaseTypeOf(dependentType))
                        {
                            qView = qView.OfType(TypeUsage.Create(dependentType));
                        }

                        if (rc.FromRole.RelationshipMultiplicity == RelationshipMultiplicity.ZeroOrOne)
                        {
                            // Filter out instances with existing relationships.
                            qView = qView.Where(e =>
                            {
                                DbExpression filter = null;
                                foreach (EdmProperty fkProp in rc.ToProperties)
                                {
                                    DbExpression notIsNull = e.Property(fkProp).IsNull().Not();
                                    filter = null == filter ? notIsNull : filter.And(notIsNull);
                                }
                                return(filter);
                            });
                        }
                        qView = qView.Select(e =>
                        {
                            List <DbExpression> ends = new List <DbExpression>();
                            foreach (AssociationEndMember end in aSet.ElementType.AssociationEndMembers)
                            {
                                if (end.Name == rc.ToRole.Name)
                                {
                                    var keyValues = new List <KeyValuePair <string, DbExpression> >();
                                    foreach (EdmMember keyMember in dependentSet.ElementType.KeyMembers)
                                    {
                                        keyValues.Add(e.Property((EdmProperty)keyMember));
                                    }
                                    ends.Add(dependentSet.RefFromKey(DbExpressionBuilder.NewRow(keyValues), dependentType));
                                }
                                else
                                {
                                    // Manufacture a key using key values.
                                    var keyValues = new List <KeyValuePair <string, DbExpression> >();
                                    foreach (EdmMember keyMember in principalSet.ElementType.KeyMembers)
                                    {
                                        int offset = rc.FromProperties.IndexOf((EdmProperty)keyMember);
                                        keyValues.Add(e.Property(rc.ToProperties[offset]));
                                    }
                                    ends.Add(principalSet.RefFromKey(DbExpressionBuilder.NewRow(keyValues), principalType));
                                }
                            }
                            return(TypeUsage.Create(aSet.ElementType).New(ends));
                        });
                        return(GeneratedView.CreateGeneratedViewForFKAssociationSet(aSet, aSet.ElementType, new DbQueryCommandTree(workspace, DataSpace.SSpace, qView), storageMappingItemCollection, m_config));
                    }
                }

                // If no User-defined QV is found, call memoized View Generation procedure.
                Dictionary <EntitySetBase, GeneratedView> generatedViews = m_generatedViewsMemoizer.Evaluate(extent.EntityContainer);

                if (!generatedViews.TryGetValue(extent, out view))
                {
                    throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.Mapping_Views_For_Extent_Not_Generated(
                                                          (extent.EntityContainer.DataSpace == DataSpace.SSpace)?"Table":"EntitySet", extent.Name));
                }

                return(view);
            }
Beispiel #17
0
 /// <summary>
 /// Get TypeReference for a type represented by a Type object
 /// </summary>
 /// <param name="type">the type object</param>
 /// <returns>the associated TypeReference object</returns>
 public CodeTypeReference ForType(Type type)
 {
     return(_forTypeMemoizer.Evaluate(type));
 }
Beispiel #18
0
 /// <summary>
 /// Get TypeReference for a bound Nullable&lt;T&gt;
 /// </summary>
 /// <param name="innerType">Type of the Nullable&lt;T&gt; type parameter</param>
 /// <returns>TypeReference for a bound Nullable&lt;T&gt;</returns>
 public CodeTypeReference NullableForType(Type innerType)
 {
     return(_nullableForTypeMemoizer.Evaluate(innerType));
 }