/// <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);
        }
		public static string GetSoftDeleteColumnName(EdmType type)
		{
			MetadataProperty annotation = type.MetadataProperties
				.SingleOrDefault(p => p.Name.EndsWith("customannotation:SoftDeleteColumnName"));

			return (string) annotation?.Value;
		}
        protected override PrepareMappingRes PrepareMapping(string typeFullName, EdmType edmItem)
        {
            string tableName = GetTableName(typeFullName);

            // find existing parent storageEntitySet
            // thp derived types does not have storageEntitySet
            EntitySet storageEntitySet;
            EdmType baseEdmType = edmItem;
            while (!EntityContainer.TryGetEntitySetByName(tableName, false, out storageEntitySet))
            {
                if (baseEdmType.BaseType == null)
                {
                    break;
                }
                baseEdmType = baseEdmType.BaseType;
            }

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

            var isRoot = baseEdmType == edmItem;
            if (!isRoot)
            {
                var parent = _entityMaps.Values.FirstOrDefault(x => x.EdmType == baseEdmType);
                // parent table has not been mapped yet
                if (parent == null)
                {
                    throw new ParentNotMappedYetException();
                }
            }

            return new PrepareMappingRes { TableName = tableName, StorageEntitySet = storageEntitySet, IsRoot = isRoot, BaseEdmType = baseEdmType };
        }
        /// <summary>
        ///     The constructor for constructing a facet description object
        /// </summary>
        /// <param name="facetName"> The name of this facet </param>
        /// <param name="facetType"> The type of this facet </param>
        /// <param name="minValue"> The min value for this facet </param>
        /// <param name="maxValue"> The max value for this facet </param>
        /// <param name="defaultValue"> The default value for this facet </param>
        /// <exception cref="System.ArgumentNullException">Thrown if either facetName, facetType or applicableType arguments are null</exception>
        internal FacetDescription(
            string facetName,
            EdmType facetType,
            int? minValue,
            int? maxValue,
            object defaultValue)
        {
            Check.NotEmpty(facetName, "facetName");
            Check.NotNull(facetType, "facetType");

            if (minValue.HasValue
                || maxValue.HasValue)
            {
                Debug.Assert(IsNumericType(facetType), "Min and Max Values can only be specified for numeric facets");

                if (minValue.HasValue
                    && maxValue.HasValue)
                {
                    Debug.Assert(minValue != maxValue, "minValue should not be equal to maxValue");
                }
            }

            _facetName = facetName;
            _facetType = facetType;
            _minValue = minValue;
            _maxValue = maxValue;
            _defaultValue = defaultValue;
        }
        internal FacetDescription(
            string facetName,
            EdmType facetType,
            int? minValue,
            int? maxValue,
            object defaultValue,
            bool isConstant,
            string declaringTypeName)
        {
            _facetName = facetName;
            _facetType = facetType;
            _minValue = minValue;
            _maxValue = maxValue;

            // this ctor doesn't allow you to set the defaultValue to null
            if (defaultValue != null)
            {
                _defaultValue = defaultValue;
            }
            else
            {
                _defaultValue = _notInitializedSentinel;
            }
            _isConstant = isConstant;

            Validate(declaringTypeName);
            if (_isConstant)
            {
                UpdateMinMaxValueForConstant(_facetName, _facetType, ref _minValue, ref _maxValue, _defaultValue);
            }
        }
        internal QueryRewriter(EdmType generatedType, ViewgenContext context, ViewGenMode typesGenerationMode)
        {
            Debug.Assert(typesGenerationMode != ViewGenMode.GenerateAllViews);

            _typesGenerationMode = typesGenerationMode;
            _context = context;
            _generatedType = generatedType;
            _domainMap = context.MemberMaps.LeftDomainMap;
            _config = context.Config;
            _identifiers = context.CqlIdentifiers;
            _qp = new RewritingProcessor<Tile<FragmentQuery>>(new DefaultTileProcessor<FragmentQuery>(context.LeftFragmentQP));
            _extentPath = new MemberPath(context.Extent);
            _keyAttributes = new List<MemberPath>(MemberPath.GetKeyMembers(context.Extent, _domainMap));

            // populate _fragmentQueries and _views
            foreach (var leftCellWrapper in _context.AllWrappersForExtent)
            {
                var query = leftCellWrapper.FragmentQuery;
                Tile<FragmentQuery> tile = CreateTile(query);
                _fragmentQueries.Add(query);
                _views.Add(tile);
            }
            Debug.Assert(_views.Count > 0);

            AdjustMemberDomainsForUpdateViews();

            // must be done after adjusting domains
            _domainQuery = GetDomainQuery(FragmentQueries, generatedType);

            _usedViews = new HashSet<FragmentQuery>();
        }
        public virtual EdmType TryCreateType(Type type, EdmType cspaceType)
        {
            DebugCheck.NotNull(type);
            DebugCheck.NotNull(cspaceType);
            Debug.Assert(cspaceType is StructuralType || Helper.IsEnumType(cspaceType), "Structural or enum type expected");

            // if one of the types is an enum while the other is not there is no match
            if (Helper.IsEnumType(cspaceType)
                ^ type.IsEnum())
            {
                LogLoadMessage(
                    Strings.Validator_OSpace_Convention_SSpaceOSpaceTypeMismatch(cspaceType.FullName, cspaceType.FullName),
                    cspaceType);
                return null;
            }

            EdmType newOSpaceType;
            if (Helper.IsEnumType(cspaceType))
            {
                TryCreateEnumType(type, (EnumType)cspaceType, out newOSpaceType);
                return newOSpaceType;
            }

            Debug.Assert(cspaceType is StructuralType);
            TryCreateStructuralType(type, (StructuralType)cspaceType, out newOSpaceType);
            return newOSpaceType;
        }
            public override void LogError(string errorMessage, EdmType relatedType)
            {
                var message = _loader.SessionData.LoadMessageLogger
                                     .CreateErrorMessageWithTypeSpecificLoadLogs(errorMessage, relatedType);

                _loader.SessionData.EdmItemErrors.Add(new EdmItemError(message));
            }
        public static string GetTenantColumnName(EdmType type)
        {
            MetadataProperty annotation =
                type.MetadataProperties.SingleOrDefault(
                    p => p.Name.EndsWith(string.Format("customannotation:{0}", TenantAnnotation)));

            return annotation == null ? null : (string)annotation.Value;
        }
        /// <summary>
        /// Gets the type identifier for the specified type.
        /// </summary>
        /// <param name="edmType">The type.</param>
        /// <returns>The identifier.</returns>
        public string Type(EdmType edmType)
        {
            if (edmType == null)
            {
                throw new ArgumentNullException("edmType");
            }

            return Identifier(edmType.Name);
        }
Exemple #11
0
        public ParameterDescriptor(string name, EdmType edmType, bool isOutParam)
        {
            Debug.Assert(name != null, "name is null");
            Debug.Assert(edmType != null, "edmType is null");

            _name = name;
            _edmType = edmType;
            _isOutParam = isOutParam;
        }
Exemple #12
0
 internal bool TryGetNamespace(EdmType item, out EdmNamespace itemNamespace)
 {
     if (item != null)
     {
         return itemToNamespaceMap.TryGetValue(item, out itemNamespace);
     }
     itemNamespace = null;
     return false;
 }
 /// <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 LogLoadMessage(string message, EdmType relatedType)
        {
            if (_logLoadMessage != null)
            {
                _logLoadMessage(message);
            }

            LogMessagesWithTypeInfo(message, relatedType);
        }
        /// <summary>
        /// A default mapping (property "Foo" maps by convention to column "Foo"), if allowed, has the lowest precedence.
        /// A mapping for a specific type (EntityType="Bar") takes precedence over a mapping for a hierarchy (EntityType="IsTypeOf(Bar)"))
        /// If there are two hierarchy mappings, the most specific mapping takes precedence. 
        /// For instance, given the types Base, Derived1 : Base, and Derived2 : Derived1, 
        /// w.r.t. Derived1 "IsTypeOf(Derived1)" takes precedence over "IsTypeOf(Base)" when you ask for the rename of Derived1
        /// </summary>
        /// <param name="lineInfo">Empty for default rename mapping.</param>
        internal string GetRename(EdmType type, out IXmlLineInfo lineInfo)
        {
            Contract.Requires(type != null);

            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>
        ///     A default mapping (property "Foo" maps by convention to column "Foo"), if allowed, has the lowest precedence.
        ///     A mapping for a specific type (EntityType="Bar") takes precedence over a mapping for a hierarchy (EntityType="IsTypeOf(Bar)"))
        ///     If there are two hierarchy mappings, the most specific mapping takes precedence.
        ///     For instance, given the types Base, Derived1 : Base, and Derived2 : Derived1,
        ///     w.r.t. Derived1 "IsTypeOf(Derived1)" takes precedence over "IsTypeOf(Base)" when you ask for the rename of Derived1
        /// </summary>
        /// <param name="lineInfo"> Empty for default rename mapping. </param>
        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;
        }
        private bool TryCreateStructuralType(Type type, StructuralType cspaceType, out EdmType newOSpaceType)
        {
            DebugCheck.NotNull(type);
            DebugCheck.NotNull(cspaceType);

            var referenceResolutionListForCurrentType = new List<Action>();
            newOSpaceType = null;

            StructuralType ospaceType;
            if (Helper.IsEntityType(cspaceType))
            {
                ospaceType = new ClrEntityType(type, cspaceType.NamespaceName, cspaceType.Name);
            }
            else
            {
                Debug.Assert(Helper.IsComplexType(cspaceType), "Invalid type attribute encountered");
                ospaceType = new ClrComplexType(type, cspaceType.NamespaceName, cspaceType.Name);
            }

            if (cspaceType.BaseType != null)
            {
                if (TypesMatchByConvention(type.BaseType(), cspaceType.BaseType))
                {
                    TrackClosure(type.BaseType());
                    referenceResolutionListForCurrentType.Add(
                        () => ospaceType.BaseType = ResolveBaseType((StructuralType)cspaceType.BaseType, type));
                }
                else
                {
                    var message = Strings.Validator_OSpace_Convention_BaseTypeIncompatible(
                        type.BaseType().FullName, type.FullName, cspaceType.BaseType.FullName);
                    LogLoadMessage(message, cspaceType);
                    return false;
                }
            }

            // Load the properties for this type
            if (!TryCreateMembers(type, cspaceType, ospaceType, referenceResolutionListForCurrentType))
            {
                return false;
            }

            // Add this to the known type map so we won't try to load it again
            LoadedTypes.Add(type.FullName, ospaceType);

            // we only add the referenceResolution to the list unless we structrually matched this type
            foreach (var referenceResolution in referenceResolutionListForCurrentType)
            {
                ReferenceResolutions.Add(referenceResolution);
            }

            newOSpaceType = ospaceType;
            return true;
        }
        private static EdmProperty CreateProperty(string name, EdmType edmType)
        {
            DebugCheck.NotEmpty(name);
            DebugCheck.NotNull(edmType);

            var typeUsage = TypeUsage.Create(edmType, new FacetValues());

            var property = new EdmProperty(name, typeUsage);

            return property;
        }
        /// <summary>
        ///     Check to see if the type is already loaded - either in the typesInLoading, or ObjectItemCollection or
        ///     in the global cache
        /// </summary>
        /// <param name="clrType"> </param>
        /// <param name="edmType"> </param>
        /// <returns> </returns>
        private bool TryGetLoadedType(Type clrType, out EdmType edmType)
        {
            if (SessionData.TypesInLoading.TryGetValue(clrType.FullName, out edmType)
                ||
                TryGetCachedEdmType(clrType, out edmType))
            {
                // Check to make sure the CLR type we got is the same as the given one
                if (edmType.ClrType != clrType)
                {
                    SessionData.EdmItemErrors.Add(
                        new EdmItemError(
                            Strings.NewTypeConflictsWithExistingType(
                                clrType.AssemblyQualifiedName, edmType.ClrType.AssemblyQualifiedName)));
                    edmType = null;
                    return false;
                }
                return true;
            }

            // Let's check to see if this type is a ref type, a nullable type, or a collection type, these are the types that
            // we need to take special care of them
            if (clrType.IsGenericType)
            {
                var genericType = clrType.GetGenericTypeDefinition();

                // Try to resolve the element type into a type object
                EdmType elementType;
                if (!TryGetLoadedType(clrType.GetGenericArguments()[0], out elementType))
                {
                    return false;
                }

                if (typeof(IEnumerable).IsAssignableFrom(clrType))
                {
                    var entityType = elementType as EntityType;
                    if (entityType == null)
                    {
                        // return null and let the caller deal with the error handling
                        return false;
                    }
                    edmType = entityType.GetCollectionType();
                }
                else
                {
                    edmType = elementType;
                }

                return true;
            }

            edmType = null;
            return false;
        }
        public static string GetSoftDeleteColumnName(EdmType type)
        {
            // TODO Find the soft delete annotation and get the property name
            //      Name of annotation will be something like:
            //      http://schemas.microsoft.com/ado/2013/11/edm/customannotation:SoftDeleteColumnName

            MetadataProperty annotation = type.MetadataProperties
                .Where(p => p.Name.EndsWith("customannotation:SoftDeleteColumnName"))
                .SingleOrDefault();

            return annotation == null ? null : (string)annotation.Value;
        }
        public string GetQualifiedPrefix(EdmType item)
        {
            Debug.Assert(ModelParentMap != null);

            string qualifiedPrefix = null;
            EdmNamespace parentNamespace;
            if (ModelParentMap.TryGetNamespace(item, out parentNamespace))
            {
                qualifiedPrefix = parentNamespace.Name;
            }

            return qualifiedPrefix;
        }
 internal bool TryGetEdmType(string typeName, out EdmType edmType)
 {
     edmType = null;
     foreach (var loadedEdmType in TypesInAssembly)
     {
         if (loadedEdmType.Identity == typeName)
         {
             edmType = loadedEdmType;
             break;
         }
     }
     return (edmType != null);
 }
Exemple #23
0
        internal static List<EdmType> GetTypeHierarchy(EdmType edmType)
        {
            Debug.Assert(edmType != null, "edmType is null");
            Debug.Assert(edmType.BuiltInTypeKind == BuiltInTypeKind.EntityType, "entity type expected");

            var types = new List<EdmType> {edmType};
            while (edmType.BaseType != null)
            {
                edmType = edmType.BaseType;
                types.Add(edmType);
            }

            return types;
        }
        private void LogMessagesWithTypeInfo(string message, EdmType relatedType)
        {
            DebugCheck.NotNull(relatedType);

            if (_messages.ContainsKey(relatedType))
            {
                // if this type already contains loading message, append the new message to the end
                _messages[relatedType].AppendLine(message);
            }
            else
            {
                _messages.Add(relatedType, new StringBuilder(message));
            }
        }
        private void LogMessagesWithTypeInfo(string message, EdmType relatedType)
        {
            Debug.Assert(relatedType != null, "have to have a type with this message");

            if (_messages.ContainsKey(relatedType))
            {
                // if this type already contains loading message, append the new message to the end
                _messages[relatedType].AppendLine(message);
            }
            else
            {
                _messages.Add(relatedType, new StringBuilder(message));
            }
        }
        /// <summary>
        ///     Returns all the FacetDescriptions for a particular type
        /// </summary>
        /// <param name="type"> the type to return FacetDescriptions for. </param>
        /// <returns> The FacetDescriptions for the type given. </returns>
        public override ReadOnlyCollection<FacetDescription> GetFacetDescriptions(EdmType type)
        {
            Debug.Assert(type is PrimitiveType, "EdmProviderManifest.GetFacetDescriptions(): Argument is not a PrimitiveType");

            InitializeFacetDescriptions();

            // Some types may not have facets, so just try to get them, if there aren't any, just return an empty list
            ReadOnlyCollection<FacetDescription> collection = null;
            if (_facetDescriptions.TryGetValue(type as PrimitiveType, out collection))
            {
                return collection;
            }
            return Helper.EmptyFacetDescriptionEnumerable;
        }
Exemple #27
0
        public FunctionDescriptor(string name, IEnumerable<ParameterDescriptor> parameters,
            EdmType[] returnTypes, string resultColumnName, string databaseSchema, StoreFunctionKind storeFunctionKind)
        {
            Debug.Assert(!string.IsNullOrWhiteSpace(name), "invalid name");
            Debug.Assert(parameters != null, "parameters is null");
            Debug.Assert(parameters.All(p => p.EdmType != null), "invalid parameter type");
            Debug.Assert(returnTypes != null && returnTypes.Length > 0, "returnTypes array is null or empty");
            Debug.Assert(storeFunctionKind == StoreFunctionKind.StoredProcedure|| returnTypes.Length == 1, "multiple return types for non-sproc");

            _name = name;
            _returnTypes = returnTypes;
            _parameters = parameters.ToArray();
            _resultColumnName = resultColumnName;
            _databaseSchema = databaseSchema;
            _storeFunctionKind = storeFunctionKind;
        }
        private string GetTypeRelatedLogMessage(EdmType relatedType)
        {
            Debug.Assert(relatedType != null, "have to pass in a type to get the message");

            if (_messages.ContainsKey(relatedType))
            {
                return new StringBuilder()
                    .AppendLine()
                    .AppendLine(Strings.ExtraInfo)
                    .AppendLine(_messages[relatedType].ToString()).ToString();
            }
            else
            {
                return string.Empty;
            }
        }
        // <summary>
        // The constructor for MetadataProperty taking in all the ingredients for creating TypeUsage and the actual value
        // </summary>
        // <param name="name"> The name of the attribute </param>
        // <param name="edmType"> The edm type of the attribute </param>
        // <param name="isCollectionType"> Whether the collection type of the given edm type should be used </param>
        // <param name="value"> The value of the attribute </param>
        internal MetadataProperty(string name, EdmType edmType, bool isCollectionType, object value)
        {
            DebugCheck.NotNull(edmType);

            _name = name;
            _value = value;
            if (isCollectionType)
            {
                _typeUsage = TypeUsage.Create(edmType.GetCollectionType());
            }
            else
            {
                _typeUsage = TypeUsage.Create(edmType);
            }
            _propertyKind = PropertyKind.System;
        }
        /// <summary>
        /// Construct a new ObjectTypeMapping object
        /// </summary>
        /// <param name="clrType"></param>
        /// <param name="cdmType"></param>
        internal ObjectTypeMapping(EdmType clrType, EdmType cdmType)
        {
            Debug.Assert(clrType.BuiltInTypeKind == cdmType.BuiltInTypeKind, "BuiltInTypeKind must be the same for both types");
            m_clrType = clrType;
            m_cdmType = cdmType;
            identity = clrType.Identity + ObjectMslConstructs.IdentitySeperator + cdmType.Identity;

            if (Helper.IsStructuralType(cdmType))
            {
                m_memberMapping = new Dictionary<string, ObjectMemberMapping>(((StructuralType)cdmType).Members.Count);
            }
            else
            {
                m_memberMapping = EmptyMemberMapping;
            }
        }
        // <summary>
        // Tries to lookup custom discriminator map for the given type (applies to EntitySets with
        // TPH discrimination pattern)
        // </summary>
        private bool TryGetDiscriminatorMap(md.EdmType type, out ExplicitDiscriminatorMap discriminatorMap)
        {
            discriminatorMap = null;

            // check that there are actually discriminator maps available
            if (null == m_discriminatorMaps)
            {
                return(false);
            }

            // must be an entity type...
            if (type.BuiltInTypeKind
                != md.BuiltInTypeKind.EntityType)
            {
                return(false);
            }

            // get root entity type (discriminator maps are mapped from the root)
            var rootEntityType = GetRootType((md.EntityType)type);

            // find entity set
            md.EntitySet entitySet;
            if (!m_entityTypeToEntitySetMap.TryGetValue(rootEntityType, out entitySet))
            {
                return(false);
            }

            // free floating entity constructors are stored with a null EntitySet
            if (entitySet == null)
            {
                return(false);
            }

            // look for discriminator map
            return(m_discriminatorMaps.TryGetValue(entitySet, out discriminatorMap));
        }
Exemple #32
0
 internal static bool IsComplexType(EdmType type)
 {
     return(BuiltInTypeKind.ComplexType == type.BuiltInTypeKind);
 }
Exemple #33
0
 internal static bool IsEntityType(EdmType type)
 {
     return(BuiltInTypeKind.EntityType == type.BuiltInTypeKind);
 }
Exemple #34
0
 // <summary>
 // Factory method for creating a TypeUsage with specified EdmType
 // </summary>
 // <param name="edmType"> EdmType for which to create a type usage </param>
 // <returns> new TypeUsage instance with default facet values </returns>
 internal static TypeUsage Create(EdmType edmType)
 {
     return(new TypeUsage(edmType));
 }
Exemple #35
0
 internal static bool IsPrimitiveType(EdmType type)
 {
     return(BuiltInTypeKind.PrimitiveType == type.BuiltInTypeKind);
 }
Exemple #36
0
        private static void AddScalarMember(
            Type type, PropertyInfo clrProperty, StructuralType ospaceType, EdmProperty cspaceProperty, EdmType propertyType)
        {
            DebugCheck.NotNull(type);
            DebugCheck.NotNull(clrProperty);
            Debug.Assert(clrProperty.CanRead && clrProperty.CanWriteExtended(), "The clr property has to have a setter and a getter.");
            DebugCheck.NotNull(ospaceType);
            DebugCheck.NotNull(cspaceProperty);
            DebugCheck.NotNull(propertyType);
            Debug.Assert(Helper.IsScalarType(propertyType), "Property has to be primitive or enum.");

            var cspaceType = cspaceProperty.DeclaringType;

            var isKeyMember = Helper.IsEntityType(cspaceType) && ((EntityType)cspaceType).KeyMemberNames.Contains(clrProperty.Name);

            // the property is nullable only if it is not a key and can actually be set to null (i.e. is not a value type or is a nullable value type)
            var nullableFacetValue = !isKeyMember
                                     &&
                                     (!clrProperty.PropertyType.IsValueType() || Nullable.GetUnderlyingType(clrProperty.PropertyType) != null);

            var ospaceProperty =
                new EdmProperty(
                    cspaceProperty.Name,
                    TypeUsage.Create(
                        propertyType, new FacetValues
            {
                Nullable = nullableFacetValue
            }),
                    clrProperty,
                    type);

            if (isKeyMember)
            {
                ((EntityType)ospaceType).AddKeyMember(ospaceProperty);
            }
            else
            {
                ospaceType.AddMember(ospaceProperty);
            }
        }
Exemple #37
0
        private void CreateAndAddNavigationProperty(
            StructuralType cspaceType, StructuralType ospaceType, NavigationProperty cspaceProperty)
        {
            EdmType ospaceRelationship;

            if (CspaceToOspace.TryGetValue(cspaceProperty.RelationshipType, out ospaceRelationship))
            {
                Debug.Assert(ospaceRelationship is StructuralType, "Structural type expected.");

                var     foundTarget = false;
                EdmType targetType  = null;
                if (Helper.IsCollectionType(cspaceProperty.TypeUsage.EdmType))
                {
                    EdmType findType;
                    foundTarget =
                        CspaceToOspace.TryGetValue(
                            ((CollectionType)cspaceProperty.TypeUsage.EdmType).TypeUsage.EdmType, out findType);
                    if (foundTarget)
                    {
                        Debug.Assert(findType is StructuralType, "Structural type expected.");

                        targetType = findType.GetCollectionType();
                    }
                }
                else
                {
                    EdmType findType;
                    foundTarget = CspaceToOspace.TryGetValue(cspaceProperty.TypeUsage.EdmType, out findType);
                    if (foundTarget)
                    {
                        Debug.Assert(findType is StructuralType, "Structural type expected.");

                        targetType = findType;
                    }
                }

                Debug.Assert(
                    foundTarget,
                    "Since the relationship will only be created if it can find the types for both ends, we will never fail to find one of the ends");

                var navigationProperty = new NavigationProperty(cspaceProperty.Name, TypeUsage.Create(targetType));
                var relationshipType   = (RelationshipType)ospaceRelationship;
                navigationProperty.RelationshipType = relationshipType;

                // we can use First because o-space relationships are created directly from
                // c-space relationship
                navigationProperty.ToEndMember =
                    (RelationshipEndMember)relationshipType.Members.First(e => e.Name == cspaceProperty.ToEndMember.Name);
                navigationProperty.FromEndMember =
                    (RelationshipEndMember)relationshipType.Members.First(e => e.Name == cspaceProperty.FromEndMember.Name);
                ospaceType.AddMember(navigationProperty);
            }
            else
            {
                var missingType =
                    cspaceProperty.RelationshipType.RelationshipEndMembers.Select(e => ((RefType)e.TypeUsage.EdmType).ElementType).First(
                        e => e != cspaceType);
                LogError(
                    Strings.Validator_OSpace_Convention_RelationshipNotLoaded(
                        cspaceProperty.RelationshipType.FullName, missingType.FullName),
                    missingType);
            }
        }
Exemple #38
0
 private MetadataPropertyAttribute(EdmType type, bool isCollectionType)
 {
     this._type             = type;
     this._isCollectionType = isCollectionType;
 }
Exemple #39
0
 /// <summary>
 ///     Check if this type is assignable from otherType
 /// </summary>
 /// <param name="otherType"> </param>
 /// <returns> </returns>
 internal virtual bool IsAssignableFrom(EdmType otherType)
 {
     return(Helper.IsAssignableFrom(this, otherType));
 }
Exemple #40
0
 internal static bool IsEnumType(EdmType edmType)
 {
     DebugCheck.NotNull(edmType);
     return(BuiltInTypeKind.EnumType == edmType.BuiltInTypeKind);
 }
Exemple #41
0
 /// <summary>
 ///     check to see if otherType is among the base types,
 /// </summary>
 /// <param name="otherType"> </param>
 /// <returns> if otherType is among the base types, return true, otherwise returns false. when othertype is same as the current type, return false. </returns>
 internal virtual bool IsSubtypeOf(EdmType otherType)
 {
     return(Helper.IsSubtypeOf(this, otherType));
 }
Exemple #42
0
 internal static bool IsScalarType(EdmType edmType)
 {
     return(IsEnumType(edmType) || IsPrimitiveType(edmType));
 }
Exemple #43
0
        /// <summary>
        ///     Load metadata of the given type - when you call this method, you should check and make sure that the type has
        ///     edm attribute. If it doesn't,we won't load the type and it will be returned as null
        /// </summary>
        /// <param name="clrType"> </param>
        /// <param name="context"> </param>
        /// <returns> </returns>
        private void LoadType(Type clrType)
        {
            Debug.Assert(clrType.Assembly == SourceAssembly, "Why are we loading a type that is not in our assembly?");
            Debug.Assert(!SessionData.TypesInLoading.ContainsKey(clrType.FullName), "Trying to load a type that is already loaded???");
            Debug.Assert(!clrType.IsGenericType, "Generic type is not supported");

            EdmType edmType = null;

            var typeAttributes = (EdmTypeAttribute[])clrType.GetCustomAttributes(typeof(EdmTypeAttribute), false /*inherit*/);

            // the CLR doesn't allow types to have duplicate/multiple attribute declarations

            if (typeAttributes.Length != 0)
            {
                if (clrType.IsNested)
                {
                    SessionData.EdmItemErrors.Add(
                        new EdmItemError(Strings.NestedClassNotSupported(clrType.FullName, clrType.Assembly.FullName)));
                    return;
                }
                var typeAttribute  = typeAttributes[0];
                var cspaceTypeName = String.IsNullOrEmpty(typeAttribute.Name) ? clrType.Name : typeAttribute.Name;
                if (String.IsNullOrEmpty(typeAttribute.NamespaceName) &&
                    clrType.Namespace == null)
                {
                    SessionData.EdmItemErrors.Add(new EdmItemError(Strings.Validator_TypeHasNoNamespace));
                    return;
                }

                var cspaceNamespaceName = String.IsNullOrEmpty(typeAttribute.NamespaceName)
                                              ? clrType.Namespace
                                              : typeAttribute.NamespaceName;

                if (typeAttribute.GetType()
                    == typeof(EdmEntityTypeAttribute))
                {
                    edmType = new ClrEntityType(clrType, cspaceNamespaceName, cspaceTypeName);
                }
                else if (typeAttribute.GetType()
                         == typeof(EdmComplexTypeAttribute))
                {
                    edmType = new ClrComplexType(clrType, cspaceNamespaceName, cspaceTypeName);
                }
                else
                {
                    Debug.Assert(typeAttribute is EdmEnumTypeAttribute, "Invalid type attribute encountered");

                    // Note that TryGetPrimitiveType() will return false not only for types that are not primitive
                    // but also for CLR primitive types that are valid underlying enum types in CLR but are not
                    // a valid Edm primitive types (e.g. ulong)
                    PrimitiveType underlyingEnumType;
                    if (!ClrProviderManifest.Instance.TryGetPrimitiveType(clrType.GetEnumUnderlyingType(), out underlyingEnumType))
                    {
                        SessionData.EdmItemErrors.Add(
                            new EdmItemError(
                                Strings.Validator_UnsupportedEnumUnderlyingType(clrType.GetEnumUnderlyingType().FullName)));

                        return;
                    }

                    edmType = new ClrEnumType(clrType, cspaceNamespaceName, cspaceTypeName);
                }
            }
            else
            {
                // not a type we are interested
                return;
            }

            Debug.Assert(
                !CacheEntry.ContainsType(edmType.Identity), "This type must not be already present in the list of types for this assembly");
            // Also add this to the list of the types for this assembly
            CacheEntry.TypesInAssembly.Add(edmType);

            // Add this to the known type map so we won't try to load it again
            SessionData.TypesInLoading.Add(clrType.FullName, edmType);

            // Load properties for structural type
            if (Helper.IsStructuralType(edmType))
            {
                //Load base type only for entity type - not sure if we will allow complex type inheritance
                if (Helper.IsEntityType(edmType))
                {
                    TrackClosure(clrType.BaseType);
                    AddTypeResolver(
                        () => edmType.BaseType = ResolveBaseType(clrType.BaseType));
                }

                // Load the properties for this type
                LoadPropertiesFromType((StructuralType)edmType);
            }

            return;
        }
Exemple #44
0
        /// <summary>
        /// Creates a <see cref="T:System.Data.Entity.Core.Metadata.Edm.TypeUsage" /> object with the specified conceptual model type.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Data.Entity.Core.Metadata.Edm.TypeUsage" /> object with the default facet values for the specified
        /// <see
        ///     cref="T:System.Data.Entity.Core.Metadata.Edm.EdmType" />
        /// .
        /// </returns>
        /// <param name="edmType">
        /// A <see cref="T:System.Data.Entity.Core.Metadata.Edm.EdmType" /> for which the
        /// <see
        ///     cref="T:System.Data.Entity.Core.Metadata.Edm.TypeUsage" />
        /// object is created.
        /// </param>
        public static TypeUsage CreateDefaultTypeUsage(EdmType edmType)
        {
            Check.NotNull(edmType, "edmType");

            return(Create(edmType));
        }
 public override void LogError(string errorMessage, EdmType relatedType)
 {
     // This is unlikely to happen since CLR types were explicitly configured by Code First
     throw new MetadataException(Strings.InvalidSchemaEncountered(errorMessage));
 }
Exemple #46
0
 public abstract void AddToTypesInAssembly(EdmType type);
Exemple #47
0
 internal static bool IsStructuralType(EdmType type)
 {
     return(IsComplexType(type) || IsEntityType(type) || IsRelationshipType(type) || IsRowType(type));
 }
 public override void AddToTypesInAssembly(EdmType type)
 {
     // No need to collect types in assembly when using Code First
 }
 public override void LogLoadMessage(string message, EdmType relatedType)
 {
     // No message logging for Code First
 }
Exemple #50
0
 internal static bool IsEntityTypeBase(EdmType edmType)
 {
     return(IsEntityType(edmType) ||
            IsRelationshipType(edmType));
 }
Exemple #51
0
 internal static bool TypesMatchByConvention(Type type, EdmType cspaceType)
 {
     return(type.Name == cspaceType.Name);
 }
Exemple #52
0
 internal static bool IsRelationshipType(EdmType type)
 {
     return(BuiltInTypeKind.AssociationType == type.BuiltInTypeKind);
 }
Exemple #53
0
 public abstract void LogLoadMessage(string message, EdmType relatedType);
Exemple #54
0
 private static IEnumerable <Facet> GetDefaultFacetDescriptionsAndOverrideFacetValues(EdmType type, FacetValues values)
 {
     return(OverrideFacetValues(
                type.GetAssociatedFacetDescriptions(),
                fd => fd,
                fd => fd.DefaultValueFacet,
                values));
 }
Exemple #55
0
 /// <summary>
 /// Factory method for creating a TypeUsage with specified EdmType and facets
 /// </summary>
 /// <param name="edmType"> EdmType for which to create a type usage </param>
 /// <param name="facets"> facets to be copied into the new TypeUsage </param>
 /// <returns> new TypeUsage instance </returns>
 public static TypeUsage Create(EdmType edmType, IEnumerable <Facet> facets)
 {
     return(new TypeUsage(edmType, facets));
 }
Exemple #56
0
 /// <summary>
 /// Returns the full name of the type described by this <see cref="T:System.Data.Entity.Core.Metadata.Edm.TypeUsage" />.
 /// </summary>
 /// <returns>
 /// The full name of the type described by this <see cref="T:System.Data.Entity.Core.Metadata.Edm.TypeUsage" /> as string.
 /// </returns>
 public override string ToString()
 {
     // Note that ToString is actually used to get the full name of the type, so changing the value returned here
     // will break code.
     return(EdmType.ToString());
 }
Exemple #57
0
 internal static bool IsTransientType(EdmType edmType)
 {
     return(IsCollectionType(edmType) ||
            IsRefType(edmType) ||
            IsRowType(edmType));
 }
Exemple #58
0
 public abstract void LogError(string errorMessage, EdmType relatedType);
Exemple #59
0
 internal CollectionType(EdmType elementType)
     : this(TypeUsage.Create(elementType))
 {
     this.DataSpace = elementType.DataSpace;
 }
Exemple #60
0
 // <summary>
 // Factory method for creating a TypeUsage with specified EdmType
 // </summary>
 // <param name="edmType"> EdmType for which to create a type usage </param>
 // <returns> new TypeUsage instance with default facet values </returns>
 internal static TypeUsage Create(EdmType edmType, FacetValues values)
 {
     return(new TypeUsage(
                edmType,
                GetDefaultFacetDescriptionsAndOverrideFacetValues(edmType, values)));
 }