public EntityContainer(string name, DataSpace dataSpace)
        {
            Check.NotEmpty(name, "name");

            _name = name;
            DataSpace = dataSpace;
            _baseEntitySets = new ReadOnlyMetadataCollection<EntitySetBase>(new EntitySetBaseCollection(this));
            _functionImports = new ReadOnlyMetadataCollection<EdmFunction>(new MetadataCollection<EdmFunction>());
        }
Beispiel #2
0
 /// <summary>
 /// Initializes a new instance of Association Type with the given name, namespace, version and ends
 /// </summary>
 /// <param name="name">name of the association type</param>
 /// <param name="namespaceName">namespace of the association type</param>
 /// <param name="foreignKey">is this a foreign key (FK) relationship?</param>
 /// <param name="dataSpace">dataSpace in which this AssociationType belongs to</param>
 /// <exception cref="System.ArgumentNullException">Thrown if either the name, namespace or version attributes are null</exception>
 internal AssociationType(string name,
                          string namespaceName,
                          bool foreignKey,
                          DataSpace dataSpace)
     : base(name, namespaceName, dataSpace)
 {
     _referentialConstraints = new ReadOnlyMetadataCollection<ReferentialConstraint>(new MetadataCollection<ReferentialConstraint>());
     _isForeignKey = foreignKey;
 }
        /// <summary>
        /// The constructor for constructing the EntityContainer object with the name, namespaceName, and version.
        /// </summary>
        /// <param name="name">The name of this entity container</param>
        /// <param name="dataSpace">dataSpace in which this entity container belongs to</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the name argument is null</exception>
        /// <exception cref="System.ArgumentException">Thrown if the name argument is empty string</exception>
        internal EntityContainer(string name, DataSpace dataSpace)
        {
            EntityUtil.CheckStringArgument(name, "name");

            _name = name;
            this.DataSpace = dataSpace;
            _baseEntitySets = new ReadOnlyMetadataCollection<EntitySetBase>(new EntitySetBaseCollection(this));
            _functionImports = new ReadOnlyMetadataCollection<EdmFunction>(new MetadataCollection<EdmFunction>());
        }
 /// <summary>
 /// Constructs a new constraint on the relationship
 /// </summary>
 /// <param name="fromRole">role from which the relationship originates</param>
 /// <param name="toRole">role to which the relationship is linked/targeted to</param>
 /// <param name="toProperties">properties on entity type of from role which take part in the constraint</param>
 /// <param name="fromProperties">properties on entity type of to role which take part in the constraint</param>
 /// <exception cref="ArgumentNullException">Argument Null exception if any of the arguments is null</exception>
 internal ReferentialConstraint(RelationshipEndMember fromRole,
                              RelationshipEndMember toRole,
                              IEnumerable<EdmProperty> fromProperties,
                              IEnumerable<EdmProperty> toProperties)
 {
     _fromRole = EntityUtil.GenericCheckArgumentNull(fromRole, "fromRole");
     _toRole = EntityUtil.GenericCheckArgumentNull(toRole, "toRole");
     _fromProperties = new ReadOnlyMetadataCollection<EdmProperty>(new MetadataCollection<EdmProperty>(
         EntityUtil.GenericCheckArgumentNull(fromProperties, "fromProperties")));
     _toProperties = new ReadOnlyMetadataCollection<EdmProperty>(new MetadataCollection<EdmProperty>(
         EntityUtil.GenericCheckArgumentNull(toProperties, "toProperties")));
 }
 /// <summary>
 ///     Constructs a new constraint on the relationship
 /// </summary>
 /// <param name="fromRole"> role from which the relationship originates </param>
 /// <param name="toRole"> role to which the relationship is linked/targeted to </param>
 /// <param name="toProperties"> properties on entity type of from role which take part in the constraint </param>
 /// <param name="fromProperties"> properties on entity type of to role which take part in the constraint </param>
 /// <exception cref="ArgumentNullException">Argument Null exception if any of the arguments is null</exception>
 public ReferentialConstraint(
     RelationshipEndMember fromRole,
     RelationshipEndMember toRole,
     IEnumerable<EdmProperty> fromProperties,
     IEnumerable<EdmProperty> toProperties)
 {
     _fromRole = Check.NotNull(fromRole, "fromRole");
     _toRole = Check.NotNull(toRole, "toRole");
     _fromProperties = new ReadOnlyMetadataCollection<EdmProperty>(
         new MetadataCollection<EdmProperty>(
             Check.NotNull(fromProperties, "fromProperties")));
     _toProperties = new ReadOnlyMetadataCollection<EdmProperty>(
         new MetadataCollection<EdmProperty>(
             Check.NotNull(toProperties, "toProperties")));
 }
        // effects: Creates a foreign key constraint of the form:
        // <i_childTable, i_childColumns> --> <i_parentTable, i_childColumns>
        // i_fkeySet is the name of the constraint
        internal ForeignConstraint(AssociationSet i_fkeySet, EntitySet i_parentTable, EntitySet i_childTable,
                                   ReadOnlyMetadataCollection<EdmProperty> i_parentColumns, ReadOnlyMetadataCollection<EdmProperty> i_childColumns)
        {
            m_fKeySet = i_fkeySet;
            m_parentTable = i_parentTable;
            m_childTable = i_childTable;
            m_childColumns = new List<MemberPath>();
            // Create parent and child paths using the table names
            foreach (EdmProperty property in i_childColumns)
            {
                MemberPath path = new MemberPath(m_childTable, property);
                m_childColumns.Add(path);
            }

            m_parentColumns = new List<MemberPath>();
            foreach (EdmProperty property in i_parentColumns)
            {
                MemberPath path = new MemberPath(m_parentTable, property);
                m_parentColumns.Add(path);
            }
        }
        private IEnumerable<DynamicFilterDefinition> FindFiltersForEntitySet(ReadOnlyMetadataCollection<MetadataProperty> metadataProperties, EntityContainer entityContainer)
        {
            var filterList = metadataProperties
                .Where(mp => mp.Name.Contains("customannotation:" + DynamicFilterConstants.ATTRIBUTE_NAME_PREFIX))
                .Select(m => m.Value as DynamicFilterDefinition)
                .ToList();

            if (filterList.Any())
            {
                //  Recursively remove any filters that exist in base EntitySets to this entity.
                //  This happens when an entity uses Table-per-Type inheritance.  Filters will be added
                //  to all derived EntitySets because of the inheritance in the C# classes.  But the database
                //  representation (the EntitySet) does not give access to inherited propeties since they
                //  only exist in the child EntitySet.  And on queries of entities involved in TPT, the
                //  query will generate a DbScanExpression for each EntitySet - so we only want the filters
                //  applied to the DbScanExpression to which they apply.
                //  See issue #32.
                RemoveFiltersForBaseClass(filterList.First().CLRType, filterList, entityContainer);
            }

            return filterList;
        }
        /// <summary>
        /// This method takes a type and a set of facets and returns the best mapped equivalent type
        /// </summary>
        /// <param name="edmType">A TypeUsage encapsulating an EDM type and a set of facets</param>
        /// <returns>A TypeUsage encapsulating a store type and a set of facets</returns>
        public override TypeUsage GetStoreType(TypeUsage edmType)
        {
            if (edmType == null)
            {
                throw new ArgumentNullException("edmType");
            }

            PrimitiveType primitiveType = edmType.EdmType as PrimitiveType;

            if (primitiveType == null)
            {
                throw new ArgumentException(String.Format("SQLite does not support the type '{0}'.", edmType));
            }

            ReadOnlyMetadataCollection <Facet> facets = edmType.Facets;

            switch (primitiveType.PrimitiveTypeKind)
            {
            case PrimitiveTypeKind.Boolean:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bit"]));

            case PrimitiveTypeKind.Byte:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["tinyint"]));

            case PrimitiveTypeKind.Int16:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["smallint"]));

            case PrimitiveTypeKind.Int32:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["int"]));

            case PrimitiveTypeKind.Int64:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["integer"]));

            case PrimitiveTypeKind.Guid:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["uniqueidentifier"]));

            case PrimitiveTypeKind.Double:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["float"]));

            case PrimitiveTypeKind.Single:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["real"]));

            case PrimitiveTypeKind.Decimal: // decimal, numeric, smallmoney, money
            {
                byte precision;
                if (!TypeHelpers.TryGetPrecision(edmType, out precision))
                {
                    precision = 18;
                }

                byte scale;
                if (!TypeHelpers.TryGetScale(edmType, out scale))
                {
                    scale = 0;
                }

                return(TypeUsage.CreateDecimalTypeUsage(StoreTypeNameToStorePrimitiveType["decimal"], precision, scale));
            }

            case PrimitiveTypeKind.Binary: // binary, varbinary, varbinary(max), image, timestamp, rowversion
            {
                bool  isFixedLength = null != facets["FixedLength"].Value && (bool)facets["FixedLength"].Value;
                Facet f             = facets["MaxLength"];

                bool isMaxLength = f.IsUnbounded || null == f.Value || (int)f.Value > Int32.MaxValue;
                int  maxLength   = !isMaxLength ? (int)f.Value : Int32.MinValue;

                TypeUsage tu;
                if (isFixedLength)
                {
                    tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["blob"], true, maxLength);
                }
                else
                {
                    if (isMaxLength)
                    {
                        tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["blob"], false);
                    }
                    else
                    {
                        tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["blob"], false, maxLength);
                    }
                }
                return(tu);
            }

            case PrimitiveTypeKind.String: // char, nchar, varchar, nvarchar, varchar(max), nvarchar(max), ntext, text
            {
                bool  isUnicode     = null == facets["Unicode"].Value || (bool)facets["Unicode"].Value;
                bool  isFixedLength = null != facets["FixedLength"].Value && (bool)facets["FixedLength"].Value;
                Facet f             = facets["MaxLength"];
                // maxlen is true if facet value is unbounded, the value is bigger than the limited string sizes *or* the facet
                // value is null. this is needed since functions still have maxlength facet value as null
                bool isMaxLength = f.IsUnbounded || null == f.Value || (int)f.Value > (isUnicode ? Int32.MaxValue : Int32.MaxValue);
                int  maxLength   = !isMaxLength ? (int)f.Value : Int32.MinValue;

                TypeUsage tu;

                if (isUnicode)
                {
                    if (isFixedLength)
                    {
                        tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["nchar"], true, true, maxLength);
                    }
                    else
                    {
                        if (isMaxLength)
                        {
                            tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["nvarchar"], true, false);
                        }
                        else
                        {
                            tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["nvarchar"], true, false, maxLength);
                        }
                    }
                }
                else
                {
                    if (isFixedLength)
                    {
                        tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["char"], false, true, maxLength);
                    }
                    else
                    {
                        if (isMaxLength)
                        {
                            tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["varchar"], false, false);
                        }
                        else
                        {
                            tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["varchar"], false, false, maxLength);
                        }
                    }
                }
                return(tu);
            }

            case PrimitiveTypeKind.DateTime: // datetime, smalldatetime
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["datetime"]));

            default:
                throw new NotSupportedException(String.Format("There is no store type corresponding to the EDM type '{0}' of primitive type '{1}'.", edmType, primitiveType.PrimitiveTypeKind));
            }
        }
Beispiel #9
0
        public override TypeUsage GetStoreType(TypeUsage edmType)
        {
            if (edmType == null)
            {
                throw new ArgumentNullException("edmType");
            }

            Debug.Assert(edmType.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType);

            PrimitiveType primitiveType = edmType.EdmType as PrimitiveType;

            if (primitiveType == null)
            {
                throw new ArgumentException(String.Format(Resources.TypeNotSupported, edmType));
            }

            ReadOnlyMetadataCollection <Facet> facets = edmType.Facets;

            switch (primitiveType.PrimitiveTypeKind)
            {
            case PrimitiveTypeKind.Boolean:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bool"]));

            case PrimitiveTypeKind.Byte:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["tinyint"]));

            case PrimitiveTypeKind.Int16:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["smallint"]));

            case PrimitiveTypeKind.Int32:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["int"]));

            case PrimitiveTypeKind.Int64:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bigint"]));

            case PrimitiveTypeKind.Guid:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["guid"]));

            case PrimitiveTypeKind.Double:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["double"]));

            case PrimitiveTypeKind.Single:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["float"]));

            case PrimitiveTypeKind.Decimal:
            {
                byte  precision = 10;
                byte  scale     = 0;
                Facet facet;

                if (edmType.Facets.TryGetValue("Precision", false, out facet))
                {
                    if (!facet.IsUnbounded && facet.Value != null)
                    {
                        precision = (byte)facet.Value;
                    }
                }

                if (edmType.Facets.TryGetValue("Scale", false, out facet))
                {
                    if (!facet.IsUnbounded && facet.Value != null)
                    {
                        scale = (byte)facet.Value;
                    }
                }

                return(TypeUsage.CreateDecimalTypeUsage(StoreTypeNameToStorePrimitiveType["decimal"], precision, scale));
            }

            case PrimitiveTypeKind.Binary:
            {
                bool  isFixedLength = null != facets["FixedLength"].Value && (bool)facets["FixedLength"].Value;
                Facet f             = facets["MaxLength"];
                bool  isMaxLength   = f.IsUnbounded || null == f.Value || (int)f.Value > MEDIUMBLOB_MAXLEN;
                int   maxLength     = !isMaxLength ? (int)f.Value : LONGBLOB_MAXLEN;

                string typeName = String.Empty;
                if (isFixedLength)
                {
                    if (maxLength < CHAR_MAXLEN)
                    {
                        typeName = "tinyblob";
                    }
                    else if (maxLength < MEDIUMBLOB_MAXLEN)
                    {
                        typeName = "blob";
                    }
                    else if (maxLength < LONGTEXT_MAXLEN)
                    {
                        typeName = "mediumblob";
                    }
                    else
                    {
                        typeName = "longblob";
                    }
                }
                else
                {
                    typeName  = isMaxLength || maxLength > BINARY_MAXLEN ? "varbinary" : "binary";
                    maxLength = isMaxLength ? VARBINARY_MAXLEN : maxLength;
                }

                return(TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType[typeName], isFixedLength, maxLength));
            }

            case PrimitiveTypeKind.String:
            {
                bool  isUnicode     = null == facets["Unicode"].Value || (bool)facets["Unicode"].Value;
                bool  isFixedLength = null != facets["FixedLength"].Value && (bool)facets["FixedLength"].Value;
                Facet f             = facets["MaxLength"];
                // maxlen is true if facet value is unbounded, the value is bigger than the limited string sizes *or* the facet
                // value is null. this is needed since functions still have maxlength facet value as null
                bool isMaxLength = f.IsUnbounded || null == f.Value || (int)f.Value > MEDIUMTEXT_MAXLEN;
                int  maxLength   = !isMaxLength ? (int)f.Value : LONGTEXT_MAXLEN;

                string typeName = String.Empty;
                if (isFixedLength)
                {
                    if (maxLength < CHAR_MAXLEN)
                    {
                        typeName = "char";
                    }
                    else if (maxLength < LONGTEXT_MAXLEN)
                    {
                        typeName = "mediumtext";
                    }
                    else
                    {
                        typeName = "longtext";
                    }
                }
                else
                {
                    typeName  = isMaxLength || maxLength > CHAR_MAXLEN ? "varchar" : "char";
                    maxLength = isMaxLength ? VARCHAR_MAXLEN : maxLength;
                }
                if (typeName.EndsWith("char") && isUnicode)
                {
                    typeName = "n" + typeName;
                }

                return(TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType[typeName], isUnicode, isFixedLength, maxLength));
            }

            case PrimitiveTypeKind.DateTimeOffset:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["timestamp"]));

            case PrimitiveTypeKind.DateTime:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["datetime"]));

            case PrimitiveTypeKind.Time:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["time"]));

            default:
                throw new NotSupportedException(String.Format(Resources.NoStoreTypeForEdmType, edmType, primitiveType.PrimitiveTypeKind));
            }
        }
Beispiel #10
0
        /// <summary>
        /// This method takes a type and a set of facets and returns the best mapped equivalent type
        /// in SQL Server, taking the store version into consideration.
        /// </summary>
        /// <param name="storeType">A TypeUsage encapsulating an EDM type and a set of facets</param>
        /// <returns>A TypeUsage encapsulating a store type and a set of facets</returns>
        public override TypeUsage GetStoreType(TypeUsage edmType)
        {
            if (edmType == null)
            {
                throw new ArgumentNullException("edmType");
            }
            System.Diagnostics.Debug.Assert(edmType.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType);

            PrimitiveType primitiveType = edmType.EdmType as PrimitiveType;

            if (primitiveType == null)
            {
                throw new ArgumentException(String.Format("The underlying provider does not support the type '{0}'.", edmType));
            }

            ReadOnlyMetadataCollection <Facet> facets = edmType.Facets;

            switch (primitiveType.PrimitiveTypeKind)
            {
            case PrimitiveTypeKind.Boolean:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["smallint_bool"]));

            case PrimitiveTypeKind.Int16:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["smallint"]));

            case PrimitiveTypeKind.Int32:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["int"]));

            case PrimitiveTypeKind.Int64:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bigint"]));

            case PrimitiveTypeKind.Double:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["double"]));

            case PrimitiveTypeKind.Single:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["float"]));

            case PrimitiveTypeKind.Decimal:                     // decimal, numeric
            {
                byte precision;
                if (!TypeHelpers.TryGetPrecision(edmType, out precision))
                {
                    precision = 9;
                }

                byte scale;
                if (!TypeHelpers.TryGetScale(edmType, out scale))
                {
                    scale = 0;
                }

                return(TypeUsage.CreateDecimalTypeUsage(StoreTypeNameToStorePrimitiveType["decimal"], precision, scale));
            }

            case PrimitiveTypeKind.Binary:                     // blob
            {
                bool  isFixedLength = null != facets[MetadataHelpers.FixedLengthFacetName].Value && (bool)facets[MetadataHelpers.FixedLengthFacetName].Value;
                Facet f             = facets[MetadataHelpers.MaxLengthFacetName];

                bool isMaxLength = f.IsUnbounded || null == f.Value || (int)f.Value > BinaryMaxSize;
                int  maxLength   = !isMaxLength ? (int)f.Value : Int32.MinValue;

                TypeUsage tu;
                if (isFixedLength)
                {
                    tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["blob"], true, maxLength);
                }
                else
                {
                    if (isMaxLength)
                    {
                        tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["blob"], false);
                        System.Diagnostics.Debug.Assert(tu.Facets["MaxLength"].Description.IsConstant, "blob is not constant!");
                    }
                    else
                    {
                        tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["blob"], false, maxLength);
                    }
                }
                return(tu);
            }

            case PrimitiveTypeKind.String:                     // char, varchar, text blob
            {
                bool  isUnicode     = null == facets[MetadataHelpers.UnicodeFacetName].Value || (bool)facets[MetadataHelpers.UnicodeFacetName].Value;
                bool  isFixedLength = null != facets[MetadataHelpers.FixedLengthFacetName].Value && (bool)facets[MetadataHelpers.FixedLengthFacetName].Value;
                Facet f             = facets[MetadataHelpers.MaxLengthFacetName];
                // maxlen is true if facet value is unbounded, the value is bigger than the limited string sizes *or* the facet
                // value is null. this is needed since functions still have maxlength facet value as null
                bool isMaxLength = f.IsUnbounded || null == f.Value || (int)f.Value > (isUnicode ? UnicodeVarcharMaxSize : AsciiVarcharMaxSize);
                int  maxLength   = !isMaxLength ? (int)f.Value : Int32.MinValue;

                TypeUsage tu;

                if (isUnicode)
                {
                    if (isFixedLength)
                    {
                        tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["char"], true, true, maxLength);
                    }
                    else
                    {
                        if (isMaxLength)
                        {
                            tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["clob"], true, false);
                        }
                        else
                        {
                            tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["varchar"], true, false, maxLength);
                        }
                    }
                }
                else
                {
                    if (isFixedLength)
                    {
                        tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["char"], false, true, maxLength);
                    }
                    else
                    {
                        if (isMaxLength)
                        {
                            tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["clob"], false, false);
                        }
                        else
                        {
                            tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["varchar"], false, false, maxLength);
                        }
                    }
                }
                return(tu);
            }

            case PrimitiveTypeKind.DateTime:                     // datetime, date
            {
                byte precision;
                bool useTimestamp;
                if (TypeHelpers.TryGetPrecision(edmType, out precision))
                {
                    if (precision == 0)
                    {
                        useTimestamp = false;
                    }
                    else
                    {
                        useTimestamp = true;
                    }
                }
                else
                {
                    useTimestamp = true;
                }

                return(TypeUsage.CreateDefaultTypeUsage(useTimestamp ? StoreTypeNameToStorePrimitiveType["timestamp"] : StoreTypeNameToStorePrimitiveType["date"]));
            }

            case PrimitiveTypeKind.Time:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["time"]));

            case PrimitiveTypeKind.Guid:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["guid"]));

            default:
                throw new NotSupportedException(string.Format("There is no store type corresponding to the EDM type '{0}' of primitive type '{1}'.", edmType, primitiveType.PrimitiveTypeKind));
            }
        }
        public string CastParameterName(TypeUsage edmType, string name)
        {
            if (edmType == null)
            {
                throw new ArgumentNullException("edmType");
            }

            PrimitiveType primitiveType = edmType.EdmType as PrimitiveType;

            if (primitiveType == null)
            {
                throw new ArgumentException(String.Format("Ingres does not support the type '{0}'.", edmType));
            }
            if (edmType == null)
            {
                throw new ArgumentNullException("edmType");
            }

            StringBuilder sb = new StringBuilder();

            ReadOnlyMetadataCollection <Facet> facets = edmType.Facets;

            switch (primitiveType.PrimitiveTypeKind)
            {
            case PrimitiveTypeKind.Boolean:
                sb.Append("boolean(" + name);
                break;

            case PrimitiveTypeKind.SByte:
                sb.Append("int1(" + name);
                break;

            case PrimitiveTypeKind.Byte:
                sb.Append("int2(" + name);
                break;

            case PrimitiveTypeKind.Int16:
                sb.Append("int2(" + name);
                break;

            case PrimitiveTypeKind.Int32:
                sb.Append("int4(" + name);
                break;

            case PrimitiveTypeKind.Int64:
                sb.Append("int8(" + name);
                break;

            case PrimitiveTypeKind.Guid:
                sb.Append("varchar(" + name);
                break;

            case PrimitiveTypeKind.Double:
                sb.Append("float8(" + name);
                break;

            case PrimitiveTypeKind.Single:
                sb.Append("float4(" + name);
                break;

            case PrimitiveTypeKind.Decimal:     // decimal, numeric, smallmoney, money
            {
                byte precision;
                if (!TypeHelpers.TryGetPrecision(edmType, out precision))
                {
                    precision = 18;
                }

                byte scale;
                if (!TypeHelpers.TryGetScale(edmType, out scale))
                {
                    scale = 0;
                }

                sb.Append(Format("decimal({0}, {1}, {2})", name, precision, scale));
                break;
            }

            case PrimitiveTypeKind.Binary:     // binary, varbinary, varbinary(max), image, timestamp, rowversion
            {
                bool isFixedLength = (null != facets["FixedLength"].Value) &&
                                     (bool)facets["FixedLength"].Value;
                Facet f = facets["MaxLength"];

                bool isMaxLength = f.IsUnbounded ||
                                   null == f.Value ||
                                   (int)f.Value > Int32.MaxValue;
                int maxLength = !isMaxLength ? (int)f.Value : Int32.MinValue;

                if (isFixedLength)
                {
                    sb.Append("binary(" + name + ", ");
                    sb.Append(maxLength.ToString());
                }
                else
                {
                    sb.Append("binary(" + name);
                }
                break;
            }

            case PrimitiveTypeKind.String:     // char, nchar, varchar, nvarchar, varchar(max), nvarchar(max), ntext, text
            {
                bool isUnicode = (null == facets["Unicode"].Value) ||
                                 (bool)facets["Unicode"].Value;
                bool isFixedLength = (null != facets["FixedLength"].Value) &&
                                     (bool)facets["FixedLength"].Value;
                Facet f = facets["MaxLength"];
                // maxlen is true if facet value is unbounded, the value is bigger than the limited string sizes *or* the facet
                // value is null. this is needed since functions still have maxlength facet value as null
                bool isMaxLength = f.IsUnbounded ||
                                   (null == f.Value) ||
                                   (int)f.Value > (isUnicode ? Int32.MaxValue : Int32.MaxValue);
                int maxLength = !isMaxLength ? (int)f.Value : Int32.MinValue;

                if (isUnicode)
                {
                    if (isFixedLength)
                    {
                        sb.Append("nchar(" + name + ", ");
                        sb.Append(maxLength.ToString());
                    }
                    else
                    {
                        sb.Append("nvarchar(" + name);
                    }
                }
                else
                {
                    if (isFixedLength)
                    {
                        sb.Append("char(" + name + ", ");
                        sb.Append(maxLength.ToString());
                    }
                    else
                    {
                        sb.Append("varchar(" + name);
                    }
                }
                break;
            }

            case PrimitiveTypeKind.DateTime:     // datetime
            {
                sb.Append("timestamp(" + name);
                break;
            }

            case PrimitiveTypeKind.Time:     // time
            {
                sb.Append("interval_dtos(" + name);
                break;
            }

            default:
            {
                break;
            }
            }  // end switch

            if (sb.Length > 0)
            {
                sb.Append(")");
                return(sb.ToString());
            }
            else
            {
                return(name);
            }
        }
Beispiel #12
0
        /// <summary>
        /// Generates SQL fragment returning server-generated values.
        /// Requires: translator knows about member values so that we can figure out
        /// how to construct the key predicate.
        /// <code>
        /// Sample SQL:
        ///
        ///     select IdentityValue
        ///     from myschema.MyTable
        ///     where __ingres_@@ROWCOUNT > 0 and IdentityValue = LAST_IDENTITY()
        ///
        ///     The "__ingres_@@ROWCOUNT" will be replaced by
        ///     the IngresDbCommandInterceptor with the number
        ///     returned for recordsAffected in the batch execution.
        ///
        /// Note that we filter on rowcount to ensure no rows are returned if no rows were modified.
        /// </code>
        /// </summary>
        /// <param name="commandText">Builder containing command text</param>
        /// <param name="tree">Modification command tree</param>
        /// <param name="translator">Translator used to produce DML SQL statement
        /// for the tree</param>
        /// <param name="returning">Returning expression. If null, the method returns
        /// immediately without producing a SELECT statement.</param>
        /// <param name="wasInsert">
        /// Non-zero if this method is being called as part of processing an INSERT;
        /// otherwise (e.g. UPDATE), zero.
        /// </param>
        private static void GenerateReturningSql(
            StringBuilder commandText,
            DbModificationCommandTree tree,
            ExpressionTranslator translator,
            DbExpression returning,
            bool wasInsert)
        {
            // Nothing to do if there is no Returning expression
            if (null == returning)
            {
                return;
            }

            commandText.Append(";"); // semicolon separated batch of SQL statements
                                     // to be executed by IngresDbCommandInterceptor
            // select
            commandText.Append("SELECT ");
            returning.Accept(translator); // e.g. "BlogId", "IntComputedValue"
            commandText.AppendLine();

            // from
            commandText.Append("FROM ");
            tree.Target.Expression.Accept(translator); // e.g. "Blogs"
            commandText.AppendLine();

            // where
            // (Ensure prior INSERT statements completed OK using recordsAffected.
            // The IngresDbCommandInterceptor will cut/paste __ingres_@@ROWCOUNT
            // with the number returned for recordsAffected.)
            commandText.Append("WHERE __ingres_@@ROWCOUNT > 0");

            EntitySetBase table = ((DbScanExpression)tree.Target.Expression).Target;
            ReadOnlyMetadataCollection <EdmMember> keyMembers =
                table.ElementType.KeyMembers;
            var hasIdentityBeenAlreadyProcessed = false;

            foreach (var keyMember in keyMembers)
            {
                commandText.Append(" AND ");
                commandText.Append(GenerateMemberTSql(keyMember));
                commandText.Append(" = ");

                // Retrieve member value sql. the translator remembers
                // member values as it constructs the INSERT/UPDATE
                // statement (which precedes the "returning" SQL SELECT)
                DbParameter value;
                if (translator.MemberValues.TryGetValue(keyMember, out value))
                {
                    commandText.Append(value.ParameterName);
                    continue; // move on to the next keyMember in keyMembers
                }

                // We have no member value to retrieve the row. Argh!

                // If INSERT then might be able to use IDENTITY.
                // Check that the column is an exact numeric data
                // type in order to qualify as an Identity column.
                if (wasInsert &&
                    IsaIdentityColumnType(keyMember.TypeUsage))
                {
                    // If no value is registered for the key member,
                    // it means it is an Identity Column value which can
                    // be retrieved using the LAST_IDENTITY() function
                    if (hasIdentityBeenAlreadyProcessed)
                    {
                        // there can be only one server generated key
                        throw new NotSupportedException(String.Format(
                                                            "Store-generated keys are only supported for " +
                                                            "identity columns. More than one key column '{0}' " +
                                                            "is marked as server generated in table '{1}'.",
                                                            (keyMember != null) ? keyMember.Name : "<unknown>",
                                                            table.Name));
                    }
                    // LAST_IDENTITY() is a sequence expression function that
                    // returns the last value generated for an identity column
                    // in any table for the current session. Since we had just done
                    // a successfull INSERT (recordsAffected > 0) of a row into a
                    // table with an identity column, we expect to retrieve that row.
                    commandText.Append("LAST_IDENTITY()");
                    hasIdentityBeenAlreadyProcessed = true;
                }    // end if (wasInsert and possible Identity column)
                else // else UPDATE or not an Identity column
                {
                    // We cannot even try to use LAST_IDENTITY() at this point
                    // because the LAST_IDENTITY() function is only valid after
                    // an INSERT and this was an UPDATE or not an Identity.
                    throw new NotSupportedException(String.Format(
                                                        "Missing value for {0} key member '{1}' in table '{2}'.",
                                                        (wasInsert) ? "INSERT" : "UPDATE",
                                                        (keyMember != null) ? keyMember.Name : "<unknown>",
                                                        table.Name));
                }
            } // end foreach (var keyMember in keyMembers)

            commandText.AppendLine(";"); // mark end of batch statements to be
                                         // executed by IngresDbCommandInterceptor
        }
Beispiel #13
0
        private static bool IsKatmaiOrNewer(EdmFunction edmFunction)
        {
            if (edmFunction.ReturnParameter != null && edmFunction.ReturnParameter.TypeUsage.IsSpatialType() || edmFunction.Parameters.Any <FunctionParameter>((Func <FunctionParameter, bool>)(p => p.TypeUsage.IsSpatialType())))
            {
                return(true);
            }
            ReadOnlyMetadataCollection <FunctionParameter> parameters = edmFunction.Parameters;

            switch (edmFunction.Name.ToUpperInvariant())
            {
            case "COUNT":
            case "COUNT_BIG":
            case "MAX":
            case "MIN":
                string name1 = ((CollectionType)parameters[0].TypeUsage.EdmType).TypeUsage.EdmType.Name;
                if (!name1.Equals("DateTimeOffset", StringComparison.OrdinalIgnoreCase))
                {
                    return(name1.Equals("Time", StringComparison.OrdinalIgnoreCase));
                }
                return(true);

            case "DAY":
            case "MONTH":
            case "YEAR":
            case "DATALENGTH":
            case "CHECKSUM":
                string name2 = parameters[0].TypeUsage.EdmType.Name;
                if (!name2.Equals("DateTimeOffset", StringComparison.OrdinalIgnoreCase))
                {
                    return(name2.Equals("Time", StringComparison.OrdinalIgnoreCase));
                }
                return(true);

            case "DATEADD":
            case "DATEDIFF":
                string name3 = parameters[1].TypeUsage.EdmType.Name;
                string name4 = parameters[2].TypeUsage.EdmType.Name;
                if (!name3.Equals("Time", StringComparison.OrdinalIgnoreCase) && !name4.Equals("Time", StringComparison.OrdinalIgnoreCase) && !name3.Equals("DateTimeOffset", StringComparison.OrdinalIgnoreCase))
                {
                    return(name4.Equals("DateTimeOffset", StringComparison.OrdinalIgnoreCase));
                }
                return(true);

            case "DATENAME":
            case "DATEPART":
                string name5 = parameters[1].TypeUsage.EdmType.Name;
                if (!name5.Equals("DateTimeOffset", StringComparison.OrdinalIgnoreCase))
                {
                    return(name5.Equals("Time", StringComparison.OrdinalIgnoreCase));
                }
                return(true);

            case "SYSUTCDATETIME":
            case "SYSDATETIME":
            case "SYSDATETIMEOFFSET":
                return(true);

            default:
                return(false);
            }
        }
Beispiel #14
0
        protected override DesignTimeMetadata GetDesignTimeMetadata(bool isDraft)
        {
            DesignTimeMetadata metadata = new DesignTimeMetadata();

            EntityContainer container     = ObjectContext.MetadataWorkspace.GetEntityContainer(ObjectContext.DefaultContainerName, DataSpace.CSpace);
            var             entitySetsDic = (from meta in container.BaseEntitySets
                                             where meta.BuiltInTypeKind == BuiltInTypeKind.EntitySet
                                             select new { EntitySetName = meta.Name, EntityTypeName = meta.ElementType.Name }).ToDictionary(es => es.EntityTypeName);


            ItemCollection CSpace = ObjectContext.MetadataWorkspace.GetItemCollection(DataSpace.CSpace);
            ItemCollection SSpace = ObjectContext.MetadataWorkspace.GetItemCollection(DataSpace.SSpace);

            EntityType[]  entityEdmTypes  = CSpace.GetItems <EntityType>().OrderBy(e => e.Name).ToArray();
            ComplexType[] complexEdmTypes = CSpace.GetItems <ComplexType>().OrderBy(e => e.Name).ToArray();

            Array.ForEach(complexEdmTypes, (entityEdmType) =>
            {
                string entityTypeName = entityEdmType.Name;
                string name           = entityTypeName;
                string[] keys         = entityEdmType.Members.Select(m => m.Name).Take(1).ToArray();
                Type entityType       = GetEntityType2(entityTypeName);
                DbSetInfo dbSetInfo   = new DbSetInfo()
                {
                    dbSetName = entityTypeName
                };
                dbSetInfo.SetEntityType(entityType);
                metadata.DbSets.Add(dbSetInfo);
                EdmProperty[] edmProps = entityEdmType.Properties.ToArray();
                GenerateFieldInfos(dbSetInfo, keys, edmProps);
            });

            Array.ForEach(entityEdmTypes, (entityEdmType) =>
            {
                if (entityEdmType.Abstract)
                {
                    return;
                }

                string entityTypeName = entityEdmType.Name;
                string name           = entityTypeName;
                if (entityEdmType.BaseType != null)
                {
                    name = entityEdmType.BaseType.Name;
                }
                string[] keys = entityEdmType.KeyMembers.Select(k => k.Name).ToArray();
                //var dbEntityEdm =  dbEntityEdmTypes[dbTableName];
                //Type entityType = this.GetEntityType(entitySetName);
                //string entitySetName = entitySetsDic[name].EntitySetName;

                Type entityType     = GetEntityType2(entityTypeName);
                DbSetInfo dbSetInfo = new DbSetInfo()
                {
                    dbSetName = entityTypeName
                };
                dbSetInfo.SetEntityType(entityType);
                metadata.DbSets.Add(dbSetInfo);
                EdmProperty[] edmProps = entityEdmType.Properties.ToArray();
                GenerateFieldInfos(dbSetInfo, keys, edmProps);
            });

            IOrderedEnumerable <AssociationType> associations = CSpace.GetItems <AssociationType>().Where(a => a.IsForeignKey).OrderBy(e => e.Name);

            Func <EdmType, string> fn_name = (EdmType n) =>
            {
                if (n.FullName.Contains('['))
                {
                    Regex  regex = new Regex(".*?\\[(.*?)\\].*?");
                    Match  match = regex.Match(n.FullName);
                    string table = match.Groups[1].Value;
                    return(table);
                }
                else
                {
                    return(n.FullName);
                }
            };

            foreach (AssociationType asstype in associations)
            {
                ReadOnlyMetadataCollection <RelationshipEndMember> endMembers = asstype.RelationshipEndMembers;

                foreach (ReferentialConstraint constraint in asstype.ReferentialConstraints)
                {
                    try
                    {
                        Association ass = metadata.Associations.Where(a => a.name == constraint.ToString()).FirstOrDefault();

                        if (ass == null)
                        {
                            RelationshipEndMember parentEnd     = (constraint.FromRole.RelationshipMultiplicity == RelationshipMultiplicity.One || constraint.FromRole.RelationshipMultiplicity == RelationshipMultiplicity.ZeroOrOne) ? constraint.FromRole : constraint.ToRole;
                            RelationshipEndMember childEnd      = constraint.FromRole == parentEnd ? constraint.ToRole : constraint.FromRole;
                            EdmType            parent           = parentEnd.TypeUsage.EdmType;
                            EdmType            child            = childEnd.TypeUsage.EdmType;
                            string             parentName       = fn_name(parent);
                            string             childName        = fn_name(child);
                            EntityType         parentEntity     = entityEdmTypes.Where(en => parentName == en.FullName).First();
                            EntityType         childEntity      = entityEdmTypes.Where(en => childName == en.FullName).First();
                            NavigationProperty parentToChildren = parentEntity.NavigationProperties.Where(np => np.FromEndMember.Name == parentEnd.Name && np.ToEndMember.Name == childEnd.Name).FirstOrDefault();
                            NavigationProperty childToParent    = childEntity.NavigationProperties.Where(np => np.FromEndMember.Name == childEnd.Name && np.ToEndMember.Name == parentEnd.Name).FirstOrDefault();

                            ass = new Association
                            {
                                name = constraint.ToString()
                            };
                            metadata.Associations.Add(ass);
                            ass.parentDbSetName      = parentEntity.Name;
                            ass.childDbSetName       = childEntity.Name;
                            ass.parentToChildrenName = parentToChildren == null ? "" : parentToChildren.Name;
                            ass.childToParentName    = childToParent == null ? "" : childToParent.Name;

                            EdmProperty[] parentArr = constraint.FromRole == parentEnd?constraint.FromProperties.ToArray() : constraint.ToProperties.ToArray();

                            EdmProperty[] childArr = constraint.FromRole == parentEnd?constraint.ToProperties.ToArray() : constraint.FromProperties.ToArray();

                            for (int i = 0; i < parentArr.Length; ++i)
                            {
                                FieldRel frel = null;
                                frel = ass.fieldRels.Where(fr => fr.parentField == parentArr[i].Name && fr.childField == childArr[i].Name).FirstOrDefault();
                                if (frel == null)
                                {
                                    frel = new FieldRel();
                                    ass.fieldRels.Add(frel);
                                    frel.parentField = parentArr[i].Name;
                                    frel.childField  = childArr[i].Name;
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
            }
            return(metadata);
        }
Beispiel #15
0
 // just for fun: get all the facet values as a Dictionary
 public static Dictionary <string, object> AsDictionary(this ReadOnlyMetadataCollection <Facet> facets)
 {
     return(facets.ToDictionary(o => o.Name, o => o.Value));
 }
Beispiel #16
0
        private bool DoPropertiesHaveDefaultNames(ReadOnlyMetadataCollection <EdmProperty> properties, ReadOnlyMetadataCollection <EdmProperty> otherEndProperties)
        {
            if (properties.Count != otherEndProperties.Count)
            {
                return(false);
            }

            return(!properties.Where((t, i) => !t.Name.EndsWith("_" + otherEndProperties[i].Name)).Any());
        }
Beispiel #17
0
        /// <summary>
        /// This method takes a type and a set of facets and returns the best mapped equivalent type
        /// in SQL Server, taking the store version into consideration.
        /// </summary>
        /// <param name="storeType">A TypeUsage encapsulating an EDM type and a set of facets</param>
        /// <returns>A TypeUsage encapsulating a store type and a set of facets</returns>
        public override TypeUsage GetStoreType(TypeUsage edmType)
        {
            if (edmType == null)
            {
                throw new ArgumentNullException("edmType");
            }
            System.Diagnostics.Debug.Assert(edmType.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType);

            PrimitiveType primitiveType = edmType.EdmType as PrimitiveType;

            if (primitiveType == null)
            {
                throw new ArgumentException(String.Format("The underlying provider does not support the type '{0}'.", edmType));
            }

            ReadOnlyMetadataCollection <Facet> facets = edmType.Facets;

            switch (primitiveType.PrimitiveTypeKind)
            {
            case PrimitiveTypeKind.Boolean:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bit"]));

            case PrimitiveTypeKind.Byte:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["tinyint"]));

            case PrimitiveTypeKind.Int16:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["smallint"]));

            case PrimitiveTypeKind.Int32:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["int"]));

            case PrimitiveTypeKind.Int64:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bigint"]));

            case PrimitiveTypeKind.Guid:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["uniqueidentifier"]));

            case PrimitiveTypeKind.Double:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["float"]));

            case PrimitiveTypeKind.Single:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["real"]));

            case PrimitiveTypeKind.Decimal:     // decimal, numeric, smallmoney, money
            {
                byte precision;
                if (!TypeHelpers.TryGetPrecision(edmType, out precision))
                {
                    precision = 18;
                }

                byte scale;
                if (!TypeHelpers.TryGetScale(edmType, out scale))
                {
                    scale = 0;
                }

                return(TypeUsage.CreateDecimalTypeUsage(StoreTypeNameToStorePrimitiveType["decimal"], precision, scale));
            }

            case PrimitiveTypeKind.Binary:     // binary, varbinary, varbinary(max), image, timestamp, rowversion
            {
                bool  isFixedLength = null != facets["FixedLength"].Value && (bool)facets["FixedLength"].Value;
                Facet f             = facets["MaxLength"];

                bool isMaxLength = f.IsUnbounded || null == f.Value || (int)f.Value > binaryMaxSize;
                int  maxLength   = !isMaxLength ? (int)f.Value : Int32.MinValue;

                TypeUsage tu;
                if (isFixedLength)
                {
                    tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["binary"], true, maxLength);
                }
                else
                {
                    if (isMaxLength)
                    {
                        tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["varbinary(max)"], false);
                        System.Diagnostics.Debug.Assert(tu.Facets["MaxLength"].Description.IsConstant, "varbinary(max) is not constant!");
                    }
                    else
                    {
                        tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["varbinary"], false, maxLength);
                    }
                }
                return(tu);
            }

            case PrimitiveTypeKind.String:
                // char, nchar, varchar, nvarchar, varchar(max), nvarchar(max), ntext, text, xml
            {
                bool  isUnicode     = null == facets["Unicode"].Value || (bool)facets["Unicode"].Value;
                bool  isFixedLength = null != facets["FixedLength"].Value && (bool)facets["FixedLength"].Value;
                Facet f             = facets["MaxLength"];
                // maxlen is true if facet value is unbounded, the value is bigger than the limited string sizes *or* the facet
                // value is null. this is needed since functions still have maxlength facet value as null
                bool isMaxLength = f.IsUnbounded || null == f.Value || (int)f.Value > (isUnicode ? nvarcharMaxSize : varcharMaxSize);
                int  maxLength   = !isMaxLength ? (int)f.Value : Int32.MinValue;

                TypeUsage tu;

                if (isUnicode)
                {
                    if (isFixedLength)
                    {
                        tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["nchar"], true, true, maxLength);
                    }
                    else
                    {
                        if (isMaxLength)
                        {
                            tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["nvarchar(max)"], true, false);
                        }
                        else
                        {
                            tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["nvarchar"], true, false, maxLength);
                        }
                    }
                }
                else
                {
                    if (isFixedLength)
                    {
                        tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["char"], false, true, maxLength);
                    }
                    else
                    {
                        if (isMaxLength)
                        {
                            tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["varchar(max)"], false, false);
                        }
                        else
                        {
                            tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["varchar"], false, false, maxLength);
                        }
                    }
                }
                return(tu);
            }

            case PrimitiveTypeKind.DateTime:     // datetime, smalldatetime

                Facet preserveSecondsFacet;
                bool  preserveSeconds;
                if (edmType.Facets.TryGetValue("PreserveSeconds", true, out preserveSecondsFacet) && null != preserveSecondsFacet.Value)
                {
                    preserveSeconds = (bool)preserveSecondsFacet.Value;
                }
                else
                {
                    preserveSeconds = true;
                }

                return(TypeUsage.CreateDefaultTypeUsage(preserveSeconds ? StoreTypeNameToStorePrimitiveType["datetime"] : StoreTypeNameToStorePrimitiveType["smalldatetime"]));

            case PrimitiveTypeKind.Geography:
            case PrimitiveTypeKind.GeographyPoint:
            case PrimitiveTypeKind.GeographyLineString:
            case PrimitiveTypeKind.GeographyPolygon:
            case PrimitiveTypeKind.GeographyMultiPoint:
            case PrimitiveTypeKind.GeographyMultiLineString:
            case PrimitiveTypeKind.GeographyMultiPolygon:
            case PrimitiveTypeKind.GeographyCollection:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["geography"]));

            case PrimitiveTypeKind.Geometry:
            case PrimitiveTypeKind.GeometryPoint:
            case PrimitiveTypeKind.GeometryLineString:
            case PrimitiveTypeKind.GeometryPolygon:
            case PrimitiveTypeKind.GeometryMultiPoint:
            case PrimitiveTypeKind.GeometryMultiLineString:
            case PrimitiveTypeKind.GeometryMultiPolygon:
            case PrimitiveTypeKind.GeometryCollection:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["geometry"]));

            default:
                throw new NotSupportedException(String.Format("There is no store type corresponding to the EDM type '{0}' of primitive type '{1}'.", edmType, primitiveType.PrimitiveTypeKind));
            }
        }
Beispiel #18
0
 // get MaxLength as an extension method to the Facets (I think the extension belongs here)
 public static int?GetMaxLength(this ReadOnlyMetadataCollection <Facet> facets)
 {
     return((int?)facets["MaxLength"].Value);
 }
Beispiel #19
0
        public override TypeUsage GetStoreType(TypeUsage edmType)
        {
            if (edmType == null)
            {
                throw new ArgumentNullException("edmType");
            }

            System.Diagnostics.Debug.Assert(edmType.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType);

            PrimitiveType primitiveType = edmType.EdmType as PrimitiveType;

            if (primitiveType == null)
            {
                throw new ArgumentException(String.Format("The underlying provider does not support the type '{0}'.", edmType));
            }

            ReadOnlyMetadataCollection <Facet> facets = edmType.Facets;
            Facet f;

            switch (primitiveType.PrimitiveTypeKind)
            {
            case PrimitiveTypeKind.Boolean:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["boolean"]));

            case PrimitiveTypeKind.Byte:
            case PrimitiveTypeKind.Int16:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["smallint"]));

            case PrimitiveTypeKind.Int32:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["integer"]));

            case PrimitiveTypeKind.Int64:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bigint"]));

            case PrimitiveTypeKind.Double:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["double"]));

            case PrimitiveTypeKind.Single:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["float"]));

            case PrimitiveTypeKind.Decimal:     // decimal, numeric
            {
                byte precision = 9;
                if (facets.TryGetValue("Precision", false, out f) && !f.IsUnbounded && f.Value != null)
                {
                    precision = (byte)f.Value;
                }
                byte scale = 0;
                if (facets.TryGetValue("Scale", false, out f) && !f.IsUnbounded && f.Value != null)
                {
                    scale = (byte)f.Value;
                }

                return(TypeUsage.CreateDecimalTypeUsage(StoreTypeNameToStorePrimitiveType["decimal"], precision, scale));
            }

            case PrimitiveTypeKind.String:     // char, varchar, text blob
            {
                bool isUnicode = true;
                if (facets.TryGetValue("Unicode", false, out f) && !f.IsUnbounded && f.Value != null)
                {
                    isUnicode = (bool)f.Value;
                }
                bool isFixedLength = true;
                if (facets.TryGetValue("FixedLength", false, out f) && !f.IsUnbounded && f.Value != null)
                {
                    isFixedLength = (bool)f.Value;
                }
                int maxLength = Int32.MinValue;
                if (facets.TryGetValue("MaxLength", false, out f) && !f.IsUnbounded && f.Value != null)
                {
                    maxLength = (int)f.Value;
                }

                PrimitiveType storePrimitiveType = StoreTypeNameToStorePrimitiveType[isFixedLength ? "char" : "varchar"];
                if (maxLength != Int32.MinValue)
                {
                    return(TypeUsage.CreateStringTypeUsage(storePrimitiveType, isUnicode, isFixedLength, maxLength));
                }

                return(TypeUsage.CreateStringTypeUsage(storePrimitiveType, isUnicode, isFixedLength));
            }

            case PrimitiveTypeKind.DateTime:     // datetime, date
            {
                byte precision = 4;
                if (facets.TryGetValue("Precision", false, out f) && !f.IsUnbounded && f.Value != null)
                {
                    precision = (byte)f.Value;
                }

                bool useTimestamp = (precision != 0);

                return(TypeUsage.CreateDefaultTypeUsage(useTimestamp ? StoreTypeNameToStorePrimitiveType["datetime"] : StoreTypeNameToStorePrimitiveType["date"]));
            }

            case PrimitiveTypeKind.Time:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["time"]));

            case PrimitiveTypeKind.Binary:     // blob
            {
                bool isFixedLength = true;
                if (facets.TryGetValue("FixedLength", false, out f) && !f.IsUnbounded && f.Value != null)
                {
                    isFixedLength = (bool)f.Value;
                }
                int maxLength = Int32.MinValue;
                if (facets.TryGetValue("MaxLength", false, out f) && !f.IsUnbounded && f.Value != null)
                {
                    maxLength = (int)f.Value;
                }

                PrimitiveType storePrimitiveType = StoreTypeNameToStorePrimitiveType["binary"];
                if (maxLength != Int32.MinValue)
                {
                    return(TypeUsage.CreateBinaryTypeUsage(storePrimitiveType, isFixedLength, maxLength));
                }

                return(TypeUsage.CreateBinaryTypeUsage(storePrimitiveType, isFixedLength));
            }

            case PrimitiveTypeKind.Guid:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["guid_char"]));

            default:
                throw new NotSupportedException(string.Format("There is no store type corresponding to the EDM type '{0}' of primitive type '{1}'.", edmType, primitiveType.PrimitiveTypeKind));
            }
        }
Beispiel #20
0
        // effects: Creates a foreign key constraint of the form:
        // <i_childTable, i_childColumns> --> <i_parentTable, i_childColumns>
        // i_fkeySet is the name of the constraint
        internal ForeignConstraint(AssociationSet i_fkeySet, EntitySet i_parentTable, EntitySet i_childTable,
                                   ReadOnlyMetadataCollection <EdmProperty> i_parentColumns, ReadOnlyMetadataCollection <EdmProperty> i_childColumns)
        {
            m_fKeySet      = i_fkeySet;
            m_parentTable  = i_parentTable;
            m_childTable   = i_childTable;
            m_childColumns = new List <MemberPath>();
            // Create parent and child paths using the table names
            foreach (EdmProperty property in i_childColumns)
            {
                MemberPath path = new MemberPath(m_childTable, property);
                m_childColumns.Add(path);
            }

            m_parentColumns = new List <MemberPath>();
            foreach (EdmProperty property in i_parentColumns)
            {
                MemberPath path = new MemberPath(m_parentTable, property);
                m_parentColumns.Add(path);
            }
        }
        /// <summary>
        /// This method takes a type and a set of facets and returns the best mapped equivalent type
        /// in SQL Server, taking the store version into consideration.
        /// </summary>
        /// <param name="storeType">A TypeUsage encapsulating an EDM type and a set of facets</param>
        /// <returns>A TypeUsage encapsulating a store type and a set of facets</returns>
        public override TypeUsage GetStoreType(TypeUsage edmType)
        {
            EntityUtil.CheckArgumentNull <TypeUsage>(edmType, "edmType");
            System.Diagnostics.Debug.Assert(edmType.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType);

            PrimitiveType primitiveType = edmType.EdmType as PrimitiveType;

            if (primitiveType == null)
            {
                throw EntityUtil.Argument(Strings.ProviderDoesNotSupportType(edmType.Identity));
            }

            ReadOnlyMetadataCollection <Facet> facets = edmType.Facets;

            switch (primitiveType.PrimitiveTypeKind)
            {
            case PrimitiveTypeKind.Boolean:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bit"]));

            case PrimitiveTypeKind.Byte:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["tinyint"]));

            case PrimitiveTypeKind.Int16:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["smallint"]));

            case PrimitiveTypeKind.Int32:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["int"]));

            case PrimitiveTypeKind.Int64:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bigint"]));

            case PrimitiveTypeKind.Geography:
            case PrimitiveTypeKind.GeographyPoint:
            case PrimitiveTypeKind.GeographyLineString:
            case PrimitiveTypeKind.GeographyPolygon:
            case PrimitiveTypeKind.GeographyMultiPoint:
            case PrimitiveTypeKind.GeographyMultiLineString:
            case PrimitiveTypeKind.GeographyMultiPolygon:
            case PrimitiveTypeKind.GeographyCollection:
                return(GetStorePrimitiveTypeIfPostSql9("geography", edmType.Identity, primitiveType.PrimitiveTypeKind));

            case PrimitiveTypeKind.Geometry:
            case PrimitiveTypeKind.GeometryPoint:
            case PrimitiveTypeKind.GeometryLineString:
            case PrimitiveTypeKind.GeometryPolygon:
            case PrimitiveTypeKind.GeometryMultiPoint:
            case PrimitiveTypeKind.GeometryMultiLineString:
            case PrimitiveTypeKind.GeometryMultiPolygon:
            case PrimitiveTypeKind.GeometryCollection:
                return(GetStorePrimitiveTypeIfPostSql9("geometry", edmType.Identity, primitiveType.PrimitiveTypeKind));

            case PrimitiveTypeKind.Guid:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["uniqueidentifier"]));

            case PrimitiveTypeKind.Double:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["float"]));

            case PrimitiveTypeKind.Single:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["real"]));

            case PrimitiveTypeKind.Decimal:     // decimal, numeric, smallmoney, money
            {
                byte precision;
                if (!TypeHelpers.TryGetPrecision(edmType, out precision))
                {
                    precision = 18;
                }

                byte scale;
                if (!TypeHelpers.TryGetScale(edmType, out scale))
                {
                    scale = 0;
                }
                TypeUsage tu = TypeUsage.CreateDecimalTypeUsage(StoreTypeNameToStorePrimitiveType["decimal"], precision, scale);
                return(tu);
            }

            case PrimitiveTypeKind.Binary:     // binary, varbinary, varbinary(max), image, timestamp, rowversion
            {
                bool  isFixedLength = null != facets[DbProviderManifest.FixedLengthFacetName].Value && (bool)facets[DbProviderManifest.FixedLengthFacetName].Value;
                Facet f             = facets[DbProviderManifest.MaxLengthFacetName];
                bool  isMaxLength   = Helper.IsUnboundedFacetValue(f) || null == f.Value || (int)f.Value > binaryMaxSize;
                int   maxLength     = !isMaxLength ? (int)f.Value : Int32.MinValue;

                TypeUsage tu;
                if (isFixedLength)
                {
                    tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["binary"], true, (isMaxLength ? binaryMaxSize : maxLength));
                }
                else
                {
                    if (isMaxLength)
                    {
                        if (_version != SqlVersion.Sql8)
                        {
                            tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["varbinary(max)"], false);
                            Debug.Assert(tu.Facets[DbProviderManifest.MaxLengthFacetName].Description.IsConstant, "varbinary(max) is not constant!");
                        }
                        else
                        {
                            tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["varbinary"], false, binaryMaxSize);
                        }
                    }
                    else
                    {
                        tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["varbinary"], false, maxLength);
                    }
                }
                return(tu);
            }

            case PrimitiveTypeKind.String:
                // char, nchar, varchar, nvarchar, varchar(max), nvarchar(max), ntext, text, xml
            {
                bool  isUnicode     = null == facets[DbProviderManifest.UnicodeFacetName].Value || (bool)facets[DbProviderManifest.UnicodeFacetName].Value;
                bool  isFixedLength = null != facets[DbProviderManifest.FixedLengthFacetName].Value && (bool)facets[DbProviderManifest.FixedLengthFacetName].Value;
                Facet f             = facets[DbProviderManifest.MaxLengthFacetName];
                // maxlen is true if facet value is unbounded, the value is bigger than the limited string sizes *or* the facet
                // value is null. this is needed since functions still have maxlength facet value as null
                bool isMaxLength = Helper.IsUnboundedFacetValue(f) || null == f.Value || (int)f.Value > (isUnicode ? nvarcharMaxSize : varcharMaxSize);
                int  maxLength   = !isMaxLength ? (int)f.Value : Int32.MinValue;

                TypeUsage tu;

                if (isUnicode)
                {
                    if (isFixedLength)
                    {
                        tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["nchar"], true, true, (isMaxLength ? nvarcharMaxSize : maxLength));
                    }
                    else
                    {
                        if (isMaxLength)
                        {
                            // nvarchar(max) (SQL 9) or ntext (SQL 8)
                            if (_version != SqlVersion.Sql8)
                            {
                                tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["nvarchar(max)"], true, false);
                                Debug.Assert(tu.Facets[DbProviderManifest.MaxLengthFacetName].Description.IsConstant, "NVarchar(max) is not constant!");
                            }
                            else
                            {
                                // if it is unknown, fallback to nvarchar[4000] instead of ntext since it has limited store semantics
                                tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["nvarchar"], true, false, nvarcharMaxSize);
                            }
                        }
                        else
                        {
                            tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["nvarchar"], true, false, maxLength);
                        }
                    }
                }
                else            // !isUnicode
                {
                    if (isFixedLength)
                    {
                        tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["char"], false, true,
                                                             (isMaxLength ? varcharMaxSize : maxLength));
                    }
                    else
                    {
                        if (isMaxLength)
                        {
                            // nvarchar(max) (SQL 9) or ntext (SQL 8)
                            if (_version != SqlVersion.Sql8)
                            {
                                tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["varchar(max)"], false, false);
                                Debug.Assert(tu.Facets[DbProviderManifest.MaxLengthFacetName].Description.IsConstant, "varchar(max) is not constant!");
                            }
                            else
                            {
                                // if it is unknown, fallback to varchar[8000] instead of text since it has limited store semantics
                                tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["varchar"], false, false, varcharMaxSize);
                            }
                        }
                        else
                        {
                            tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["varchar"], false, false, maxLength);
                        }
                    }
                }
                return(tu);
            }


            case PrimitiveTypeKind.DateTime:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["datetime"]));

            case PrimitiveTypeKind.DateTimeOffset:
                return(GetStorePrimitiveTypeIfPostSql9("datetimeoffset", edmType.Identity, primitiveType.PrimitiveTypeKind));

            case PrimitiveTypeKind.Time:
                return(GetStorePrimitiveTypeIfPostSql9("time", edmType.Identity, primitiveType.PrimitiveTypeKind));

            default:
                throw EntityUtil.NotSupported(Strings.NoStoreTypeForEdmType(edmType.Identity, primitiveType.PrimitiveTypeKind));
            }
        }
Beispiel #22
0
        private bool DoPropertiesHaveDefaultNames(ReadOnlyMetadataCollection <EdmProperty> properties, string roleName, ReadOnlyMetadataCollection <EdmProperty> otherEndProperties)
        {
            if (properties.Count != otherEndProperties.Count)
            {
                return(false);
            }

            for (int i = 0; i < properties.Count; ++i)
            {
                if (!properties[i].Name.EndsWith("_" + otherEndProperties[i].Name))
                {
                    return(false);
                }
            }
            return(true);
        }
        /// <summary>
        /// Main code generator method.
        /// </summary>
        /// <param name="namespaceString">Namespace where the class will reside</param>
        /// <param name="className">Generated class name</param>
        /// <param name="attributeNamespace">The 'EdmFunction' attribute parameter</param>
        /// <param name="pascalCaseFunctionNames">If the input function names need to be pascal cased.</param>
        public StringWriter GenerateCode(string namespaceString, string className, string attributeNamespace, Boolean pascalCaseFunctionNames)
        {
            StringWriter newCode = new StringWriter();
            Boolean      isAggregateFunction;
            bool         hasSByteParameterOrReturnType;
            bool         hasStringInParameterName;
            String       separator;

            GenerateFileHeader(newCode, className);
            GenerateUsingStatements(newCode);

            newCode.WriteLine("namespace " + namespaceString);
            newCode.WriteLine("{");

            GenerateClassHeader(newCode, className, attributeNamespace);

            foreach (System.Data.Metadata.Edm.EdmFunction function in _functions)
            {
                isAggregateFunction           = false;
                hasSByteParameterOrReturnType = false;
                hasStringInParameterName      = false;
                separator = "";

                String functionNameToUse = FindCorrectFunctionName(function.Name, pascalCaseFunctionNames);
                GenerateFunctionHeader(newCode, attributeNamespace, function.Name);
                Type returnType = ((PrimitiveType)(function.ReturnParameter.TypeUsage.EdmType)).ClrEquivalentType;

                //Suppress warning that 'SByte' is not CLS-compliant.
                if (returnType == typeof(SByte))
                {
                    hasSByteParameterOrReturnType = true;
                }
                StringBuilder functionSignatureString = new StringBuilder();
                AppendSpaces(functionSignatureString, 8);
                functionSignatureString.Append("public static ");
                WriteType(functionSignatureString, returnType);
                functionSignatureString.Append(functionNameToUse + "(");

                ReadOnlyMetadataCollection <FunctionParameter> functionParameters = function.Parameters;
                Type parameterType;
                foreach (System.Data.Metadata.Edm.FunctionParameter parameter in functionParameters)
                {
                    String parameterNameToUse = parameter.Name;
                    parameterNameToUse = FindCorrectParameterName(parameterNameToUse);

                    //Detect aggregate functions. They have just one parameter and so stub can be generated here.
                    if (parameter.TypeUsage.EdmType.GetType() == typeof(System.Data.Metadata.Edm.CollectionType))
                    {
                        isAggregateFunction = true;
                        if (parameterNameToUse.ToLowerInvariant().Contains("string"))
                        {
                            hasStringInParameterName = true;
                        }

                        System.Data.Metadata.Edm.CollectionType collectionType = (System.Data.Metadata.Edm.CollectionType)parameter.TypeUsage.EdmType;
                        parameterType = ((PrimitiveType)(collectionType.TypeUsage.EdmType)).ClrEquivalentType;
                        //Detect if there is an 'SByte' parameter to suppress non-CLS-compliance warning.
                        //Generate the attribute only once for each function.
                        if (parameterType == typeof(SByte))
                        {
                            hasSByteParameterOrReturnType = true;
                        }

                        //Generate stub for non-nullable input parameters
                        functionSignatureString.Append("IEnumerable<" + parameterType.ToString());
                        //Supress fxcop message and CLS non-compliant attributes
                        GenerateFunctionAttributes(newCode, hasStringInParameterName, hasSByteParameterOrReturnType);
                        //Use the constructed function signature
                        newCode.Write(functionSignatureString.ToString());
                        GenerateAggregateFunctionStub(newCode, parameterType, returnType, parameterNameToUse, false);

                        //Generate stub for nullable input parameters
                        //Special Case: Do not generate nullable stub for input parameter of types Byte[]
                        //and String, since they are nullable.
                        if (!IsNullableType(parameterType))
                        {
                            GenerateFunctionHeader(newCode, attributeNamespace, function.Name);
                            //Supress fxcop message and CLS non-compliant attributes
                            GenerateFunctionAttributes(newCode, hasStringInParameterName, hasSByteParameterOrReturnType);
                            //Use the constructed function signature
                            newCode.Write(functionSignatureString.ToString());
                            GenerateAggregateFunctionStub(newCode, parameterType, returnType, parameterNameToUse, true);
                        }
                    } //End of processing parameters for aggregate functions.
                    //Process each parameter in case of non-aggregate functions.
                    else
                    {
                        parameterType = ((PrimitiveType)(parameter.TypeUsage.EdmType)).ClrEquivalentType;
                        functionSignatureString.Append(separator);
                        WriteType(functionSignatureString, parameterType);
                        functionSignatureString.Append(parameterNameToUse);
                        separator = ", ";
                        //Detect if there is an 'SByte' parameter to suppress non-CLS-compliance warning.
                        if (parameterType == typeof(SByte))
                        {
                            hasSByteParameterOrReturnType = true;
                        }
                        if (parameterNameToUse.ToLowerInvariant().Contains("string"))
                        {
                            hasStringInParameterName = true;
                        }
                    }
                } //End for each parameter

                //Generate stub for Non-aggregate functions after all input parameters are found.
                if (!isAggregateFunction)
                {
                    //Supress fxcop supression and CLS non-compliant attributes
                    GenerateFunctionAttributes(newCode, hasStringInParameterName, hasSByteParameterOrReturnType);
                    newCode.WriteLine(functionSignatureString.ToString() + ")");
                    AppendSpaces(newCode, 8);
                    newCode.WriteLine("{");
                    WriteExceptionStatement(newCode);
                }
            } //End for each function

            AppendSpaces(newCode, 4);
            newCode.WriteLine("}");
            newCode.WriteLine("}");
            newCode.Close();
            return(newCode);
        }
 private void ResetEntitySetsCache(object sender, EventArgs e)
 {
     if (_entitySetsCache != null)
     {
         lock (_baseEntitySetsLock)
         {
             if (_entitySetsCache != null)
             {
                 _entitySetsCache = null;
                 _baseEntitySets.SourceAccessed -= ResetEntitySetsCache;
             }
         }
     }
 }
        static bool DoPropertiesHaveDefaultNames(ReadOnlyMetadataCollection <EdmProperty> properties, ReadOnlyMetadataCollection <EdmProperty> otherEndProperties)
        {
            if (properties.Count != otherEndProperties.Count)
            {
                return(false);
            }

            for (int i = 0; i < properties.Count; ++i)
            {
                if (!properties[i].Name.EndsWith("_" + otherEndProperties[i].Name, StringComparison.OrdinalIgnoreCase))
                {
                    return(false);
                }
            }
            return(true);
        }
        private static bool IsKatmaiOrNewer(EdmFunction edmFunction)
        {
            // Spatial types are only supported from Katmai onward; any functions using them must therefore also be Katmai or newer.
            if ((edmFunction.ReturnParameter != null && Helper.IsSpatialType(edmFunction.ReturnParameter.TypeUsage)) ||
                edmFunction.Parameters.Any(p => Helper.IsSpatialType(p.TypeUsage)))
            {
                return(true);
            }

            ReadOnlyMetadataCollection <FunctionParameter> funParams = edmFunction.Parameters;

            switch (edmFunction.Name.ToUpperInvariant())
            {
            case "COUNT":
            case "COUNT_BIG":
            case "MAX":
            case "MIN":
            {
                string name = ((CollectionType)funParams[0].TypeUsage.EdmType).TypeUsage.EdmType.Name;
                return((name.Equals("DateTimeOffset", StringComparison.OrdinalIgnoreCase)) ||
                       (name.Equals("Time", StringComparison.OrdinalIgnoreCase)));
            }

            case "DAY":
            case "MONTH":
            case "YEAR":
            case "DATALENGTH":
            case "CHECKSUM":
            {
                string name = funParams[0].TypeUsage.EdmType.Name;
                return((name.Equals("DateTimeOffset", StringComparison.OrdinalIgnoreCase)) ||
                       (name.Equals("Time", StringComparison.OrdinalIgnoreCase)));
            }

            case "DATEADD":
            case "DATEDIFF":
            {
                string param1Name = funParams[1].TypeUsage.EdmType.Name;
                string param2Name = funParams[2].TypeUsage.EdmType.Name;
                return((param1Name.Equals("Time", StringComparison.OrdinalIgnoreCase)) ||
                       (param2Name.Equals("Time", StringComparison.OrdinalIgnoreCase)) ||
                       (param1Name.Equals("DateTimeOffset", StringComparison.OrdinalIgnoreCase)) ||
                       (param2Name.Equals("DateTimeOffset", StringComparison.OrdinalIgnoreCase)));
            }

            case "DATENAME":
            case "DATEPART":
            {
                string name = funParams[1].TypeUsage.EdmType.Name;
                return((name.Equals("DateTimeOffset", StringComparison.OrdinalIgnoreCase)) ||
                       (name.Equals("Time", StringComparison.OrdinalIgnoreCase)));
            }

            case "SYSUTCDATETIME":
            case "SYSDATETIME":
            case "SYSDATETIMEOFFSET":
                return(true);

            default:
                break;
            }

            return(false);
        }
        private static void PopulateDataTable <TEnity>(DataTable dataTable, ObjectContext objectContext, IList <TEnity> list, ReadOnlyMetadataCollection <EdmMember> storageSpaceMembers) where TEnity : class
        {
            Type typeOfEntity = typeof(TEnity);
            ReadOnlyMetadataCollection <EdmMember> objectSpaceMembers = objectContext.MetadataWorkspace.GetItem <EntityType>(typeOfEntity.FullName, true, DataSpace.OSpace).Members;
            EntitySetBase entitySetBase = objectContext.MetadataWorkspace.GetEntityContainer(objectContext.DefaultContainerName, DataSpace.CSpace).BaseEntitySets.FirstOrDefault(baseEntitySet => baseEntitySet.ElementType.Name.Equals(typeOfEntity.Name, StringComparison.OrdinalIgnoreCase));
            EntityType    entityType    = (EntityType)entitySetBase.ElementType;

            foreach (TEnity entity in list)
            {
                DataRow dataRow = dataTable.NewRow();
                foreach (EdmProperty edmProperty in entityType.Properties)
                {
                    dataRow[storageSpaceMembers[objectSpaceMembers.IndexOf(objectSpaceMembers[edmProperty.Name])].Name] = (GetPropertyValue <object>(entity, edmProperty.Name) == null)?DBNull.Value: GetPropertyValue <object>(entity, edmProperty.Name);
                }

                if (entityType.NavigationProperties.Count > 0)
                {
                    ICollection <ReferentialConstraint> referentialConstraints = GetReferentialConstraints(objectContext, typeOfEntity, entitySetBase);

                    foreach (NavigationProperty navigationProperty in entityType.NavigationProperties)
                    {
                        IEnumerable <ReferentialConstraint> filteredReferentialConstraints = referentialConstraints.Where(referentialConstraint => referentialConstraint.FromRole.Name.Equals(navigationProperty.Name, StringComparison.OrdinalIgnoreCase));

                        foreach (ReferentialConstraint referentialConstraint in filteredReferentialConstraints)
                        {
                            dataRow[referentialConstraint.ToProperties[0].Name] = GetPropertyValue <object>(GetPropertyValue <object>(entity, referentialConstraint.FromRole.Name), referentialConstraint.FromProperties[0].Name);
                        }
                    }
                }

                dataTable.Rows.Add(dataRow);
            }
        }
        private IEnumerable<DynamicFilterDefinition> FindFiltersForEntitySet(ReadOnlyMetadataCollection<MetadataProperty> metadataProperties)
        {
            var configuration = metadataProperties.FirstOrDefault(p => p.Name == "Configuration")?.Value;
            if (configuration == null)
                return new List<DynamicFilterDefinition>();

            //  The "Annotations" property will not exist if this is a navigation property (because configuration
            //  is a NavigationPropertyConfiguration object not an EntityTypeConfiguration object.
            //  That happens if we use the entry.Load() command to load a child collection.  See issue #71.
            var annotations = configuration.GetType().GetProperty("Annotations")?.GetValue(configuration, null) as Dictionary<string, object>;
            if (annotations == null)
                return new List<DynamicFilterDefinition>();

            var filterList = annotations.Select(a => a.Value as DynamicFilterDefinition).Where(a => a != null).ToList();

            //  Note: Prior to the switch to use CSpace (which was done to allow filters on navigation properties),
            //  we had to remove filters that exist in base EntitySets to this entity to fix issues with 
            //  Table-per-Type inheritance (issue #32).  In CSpace none of that is necessary since we are working
            //  with the actual c# models now (in CSpace) so we always have the correct filters and access to all
            //  the inherited properties that we need.

            return filterList;
        }
Beispiel #29
0
        //"doFixup" equals to False is called from EntityCollection & Ref code only
        internal void Delete(bool doFixup)
        {
            ValidateState();

            if (doFixup)
            {
                if (State != EntityState.Deleted)  //for deleted ObjectStateEntry its a no-op
                {
                    //Find two ends of the relationship
                    EntityEntry    entry1         = _cache.GetEntityEntry((EntityKey)GetCurrentRelationValue(0));
                    IEntityWrapper wrappedEntity1 = entry1.WrappedEntity;
                    EntityEntry    entry2         = _cache.GetEntityEntry((EntityKey)GetCurrentRelationValue(1));
                    IEntityWrapper wrappedEntity2 = entry2.WrappedEntity;

                    // If one end of the relationship is a KeyEntry, entity1 or entity2 is null.
                    // It is not possible that both ends of relationship are KeyEntries.
                    if (wrappedEntity1.Entity != null && wrappedEntity2.Entity != null)
                    {
                        // Obtain the ro role name and relationship name
                        // We don't create a full NavigationRelationship here because that would require looking up
                        // additional information like property names that we don't need.
                        ReadOnlyMetadataCollection <AssociationEndMember> endMembers = _relationshipWrapper.AssociationEndMembers;
                        string toRole           = endMembers[1].Name;
                        string relationshipName = ((AssociationSet)_entitySet).ElementType.FullName;
                        wrappedEntity1.RelationshipManager.RemoveEntity(toRole, relationshipName, wrappedEntity2);
                    }
                    else
                    {
                        // One end of relationship is a KeyEntry, figure out which one is the real entity and get its RelationshipManager
                        // so we can update the DetachedEntityKey on the EntityReference associated with this relationship
                        EntityKey           targetKey           = null;
                        RelationshipManager relationshipManager = null;
                        if (wrappedEntity1.Entity == null)
                        {
                            targetKey           = entry1.EntityKey;
                            relationshipManager = wrappedEntity2.RelationshipManager;
                        }
                        else
                        {
                            targetKey           = entry2.EntityKey;
                            relationshipManager = wrappedEntity1.RelationshipManager;
                        }
                        Debug.Assert(relationshipManager != null, "Entity wrapper returned a null RelationshipManager");

                        // Clear the detachedEntityKey as well. In cases where we have to fix up the detachedEntityKey, we will not always be able to detect
                        // if we have *only* a Deleted relationship for a given entity/relationship/role, so clearing this here will ensure that
                        // even if no other relationships are added, the key value will still be correct and we won't accidentally pick up an old value.

                        // devnote: Since we know the target end of this relationship is a key entry, it has to be a reference, so just cast
                        AssociationEndMember targetMember    = this.RelationshipWrapper.GetAssociationEndMember(targetKey);
                        EntityReference      entityReference = (EntityReference)relationshipManager.GetRelatedEndInternal(targetMember.DeclaringType.FullName, targetMember.Name);
                        entityReference.DetachedEntityKey = null;

                        // Now update the state
                        if (this.State == EntityState.Added)
                        {
                            // Remove key entry if necessary
                            DeleteUnnecessaryKeyEntries();
                            // Remove relationship entry
                            // devnote: Using this method instead of just changing the state because the entry
                            //          may have already been detached along with the key entry above. However,
                            //          if there were other relationships using the key, it would not have been deleted.
                            DetachRelationshipEntry();
                        }
                        else
                        {
                            // Non-added entries should be deleted
                            _cache.ChangeState(this, this.State, EntityState.Deleted);
                            State = EntityState.Deleted;
                        }
                    }
                }
            }
            else
            {
                switch (State)
                {
                case EntityState.Added:
                    // Remove key entry if necessary
                    DeleteUnnecessaryKeyEntries();
                    // Remove relationship entry
                    // devnote: Using this method instead of just changing the state because the entry
                    //          may have already been detached along with the key entry above. However,
                    //          if there were other relationships using the key, it would not have been deleted.
                    DetachRelationshipEntry();
                    break;

                case EntityState.Modified:
                    Debug.Assert(false, "RelationshipEntry cannot be in Modified state");
                    break;

                case EntityState.Unchanged:
                    _cache.ChangeState(this, EntityState.Unchanged, EntityState.Deleted);
                    State = EntityState.Deleted;
                    break;
                    //case DataRowState.Deleted:  no-op
                }
            }
        }
        /// <summary>
        /// Emit static factory method which creates an instance of the class and initializes
        /// non-nullable properties (taken as arguments)
        /// </summary>
        /// <param name="typeDecl"></param>
        protected virtual void EmitFactoryMethod(CodeTypeDeclaration typeDecl)
        {
            // build list of non-nullable properties
            ReadOnlyMetadataCollection <EdmProperty> properties = GetProperties();
            List <EdmProperty> parameters = new List <EdmProperty>(properties.Count);

            foreach (EdmProperty property in properties)
            {
                bool include = IncludeFieldInFactoryMethod(property);
                if (include)
                {
                    parameters.Add(property);
                }
            }

            // if there are no parameters, we don't emit anything (1 is for the null element)
            // nor do we emit everything if this is the Ref propertied ctor and the parameter list is the same as the many parametered ctor
            if (parameters.Count < 1)
            {
                return;
            }

            CodeMemberMethod        method  = new CodeMemberMethod();
            CodeTypeReference       typeRef = TypeReference.FromString(Item.Name);
            UniqueIdentifierService uniqueIdentifierService = new UniqueIdentifierService(Generator.IsLanguageCaseSensitive);
            string instanceName = uniqueIdentifierService.AdjustIdentifier(Utils.CamelCase(Item.Name));

            // public static Class CreateClass(...)
            method.Attributes = MemberAttributes.Static | MemberAttributes.Public;
            method.Name       = "Create" + Item.Name;
            if (NavigationPropertyEmitter.IsNameAlreadyAMemberName(Item, method.Name, Generator.LanguageAppropriateStringComparer))
            {
                Generator.AddError(Strings.GeneratedFactoryMethodNameConflict(method.Name, Item.Name),
                                   ModelBuilderErrorCode.GeneratedFactoryMethodNameConflict,
                                   EdmSchemaErrorSeverity.Error);
            }

            method.ReturnType = typeRef;
            AttributeEmitter.AddGeneratedCodeAttribute(method);

            // output method summary comments
            CommentEmitter.EmitSummaryComments(Strings.FactoryMethodSummaryComment(Item.Name), method.Comments);


            // Class class = new Class();
            CodeVariableDeclarationStatement createNewInstance = new CodeVariableDeclarationStatement(
                typeRef, instanceName, new CodeObjectCreateExpression(typeRef));

            method.Statements.Add(createNewInstance);
            CodeVariableReferenceExpression instanceRef = new CodeVariableReferenceExpression(instanceName);

            // iterate over the properties figuring out which need included in the factory method
            foreach (EdmProperty property in parameters)
            {
                // CreateClass( ... , propType propName ...)
                PropertyEmitter   propertyEmitter       = new PropertyEmitter(Generator, property, UsingStandardBaseClass);
                CodeTypeReference propertyTypeReference = propertyEmitter.PropertyType;
                String            parameterName         = uniqueIdentifierService.AdjustIdentifier(Utils.FixParameterName(propertyEmitter.PropertyName, "argument"));
                parameterName = Utils.SetSpecialCaseForFxCopOnPropertyName(parameterName);
                CodeParameterDeclarationExpression paramDecl = new CodeParameterDeclarationExpression(
                    propertyTypeReference, parameterName);
                CodeArgumentReferenceExpression paramRef = new CodeArgumentReferenceExpression(paramDecl.Name);
                method.Parameters.Add(paramDecl);

                // add comment describing the parameter
                CommentEmitter.EmitParamComments(paramDecl, Strings.FactoryParamCommentGeneral(propertyEmitter.PropertyName), method.Comments);

                CodeExpression newPropertyValue;
                if (TypeSemantics.IsComplexType(propertyEmitter.Item.TypeUsage))
                {
                    List <CodeExpression> complexVerifyParameters = new List <CodeExpression>();
                    complexVerifyParameters.Add(paramRef);
                    complexVerifyParameters.Add(new CodePrimitiveExpression(propertyEmitter.PropertyName));

                    // if (null == param) { throw new ArgumentNullException("PropertyName"); }
                    method.Statements.Add(
                        new CodeConditionStatement(
                            EmitExpressionEqualsNull(paramRef),
                            new CodeThrowExceptionStatement(
                                new CodeObjectCreateExpression(
                                    TypeReference.ForType(typeof(ArgumentNullException)),
                                    new CodePrimitiveExpression(parameterName)
                                    )
                                )
                            )
                        );

                    newPropertyValue = paramRef;
                }
                else
                {
                    newPropertyValue = paramRef;
                }

                // Scalar property:
                //     Property = param;
                // Complex property:
                //     Property = StructuralObject.VerifyComplexObjectIsNotNull(param, propertyName);

                method.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(instanceRef, propertyEmitter.PropertyName), newPropertyValue));
            }

            // return class;
            method.Statements.Add(new CodeMethodReturnStatement(instanceRef));

            // actually add the method to the class
            typeDecl.Members.Add(method);
        }
 internal void ResetKeyPropertiesCache()
 {
     // PERF: this code written this way since it's part of a hotpath, consider its performance when refactoring. See codeplex #2298.
     if (_keyProperties != null)
     {
         lock (_keyPropertiesSync)
         {
             if (_keyProperties != null)
             {
                 _keyProperties = null;
                 KeyMembers.SourceAccessed -= KeyMembersSourceAccessedEventHandler;
             }
         }
     }
 }
 private static string GetTableNameByClrName(ReadOnlyMetadataCollection<EntitySet> EntitySets,string tablename)
 {
     return EntitySets.First(x=>x.Name == tablename).Table;
 }
        public override TypeUsage GetStoreType(TypeUsage edmType)
        {
            bool bUse32DataTypes = ODTSettings.m_bUse32DataTypes;

            if (EFProviderSettings.s_tracingEnabled)
            {
                EFProviderSettings.Instance.Trace(EFProviderSettings.EFTraceLevel.Entry, " (ENTRY) EFOracleProviderManifest::GetStoreType() \n");
            }
            EntityUtils.CheckArgumentNull <TypeUsage>(edmType, nameof(edmType));
            PrimitiveType edmType1 = edmType.EdmType as PrimitiveType;

            if (edmType1 == null)
            {
                throw new ArgumentException(EFProviderSettings.Instance.GetErrorMessage(-1703, "Oracle Data Provider for .NET", edmType.EdmType.FullName));
            }
            ReadOnlyMetadataCollection <Facet> facets = edmType.Facets;

            if (EFProviderSettings.s_tracingEnabled)
            {
                EFProviderSettings.Instance.Trace(EFProviderSettings.EFTraceLevel.Entry, " (EXIT) EFOracleProviderManifest::GetStoreType() \n");
            }
            switch (edmType1.PrimitiveTypeKind)
            {
            case PrimitiveTypeKind.Binary:
                bool  flag1      = facets["FixedLength"].Value != null && (bool)facets["FixedLength"].Value;
                Facet facet1     = facets["MaxLength"];
                bool  flag2      = !bUse32DataTypes ? facet1.IsUnbounded || facet1.Value == null || (int)facet1.Value > 2000 : facet1.IsUnbounded || facet1.Value == null || (int)facet1.Value > this.BinaryMaxSize_12c;
                int   maxLength1 = !flag2 ? (int)facet1.Value : int.MinValue;
                return(!flag1 ? (!flag2 ? TypeUsage.CreateBinaryTypeUsage(this.StoreTypeNameToStorePrimitiveType["raw"], false, maxLength1) : TypeUsage.CreateBinaryTypeUsage(this.StoreTypeNameToStorePrimitiveType["blob"], false)) : (!bUse32DataTypes ? TypeUsage.CreateBinaryTypeUsage(this.StoreTypeNameToStorePrimitiveType["raw"], true, flag2 ? 2000 : maxLength1) : TypeUsage.CreateBinaryTypeUsage(this.StoreTypeNameToStorePrimitiveType["raw"], true, flag2 ? this.BinaryMaxSize_12c : maxLength1)));

            case PrimitiveTypeKind.Boolean:
                return(TypeUsage.CreateDecimalTypeUsage(this.StoreTypeNameToStorePrimitiveType["number"], (byte)EFOracleProviderManifest.m_edmMappingMaxBOOL, (byte)0));

            case PrimitiveTypeKind.Byte:
                return(TypeUsage.CreateDecimalTypeUsage(this.StoreTypeNameToStorePrimitiveType["number"], (byte)EFOracleProviderManifest.m_edmMappingMaxBYTE, (byte)0));

            case PrimitiveTypeKind.DateTime:
                if (facets == null || facets["Precision"].Value == null)
                {
                    return(TypeUsage.CreateDefaultTypeUsage((EdmType)this.StoreTypeNameToStorePrimitiveType["date"]));
                }
                if ((int)(byte)facets["Precision"].Value > 9)
                {
                    return(TypeUsage.CreateDefaultTypeUsage((EdmType)this.StoreTypeNameToStorePrimitiveType["timestamp with local time zone"]));
                }
                return(TypeUsage.CreateDefaultTypeUsage((EdmType)this.StoreTypeNameToStorePrimitiveType["timestamp"]));

            case PrimitiveTypeKind.Decimal:
                byte precision;
                byte scale;
                if (EF6MetadataHelpers.TryGetPrecision(edmType, out precision) && EF6MetadataHelpers.TryGetScale(edmType, out scale))
                {
                    if ((int)precision == 250 && (int)scale == 0)
                    {
                        return(TypeUsage.CreateDecimalTypeUsage(this.StoreTypeNameToStorePrimitiveType["interval year to month"], (byte)9, (byte)0));
                    }
                    if ((int)precision == 251 && (int)scale == 0)
                    {
                        return(TypeUsage.CreateDecimalTypeUsage(this.StoreTypeNameToStorePrimitiveType["interval day to second"], (byte)9, (byte)0));
                    }
                    return(TypeUsage.CreateDecimalTypeUsage(this.StoreTypeNameToStorePrimitiveType["number"], precision, scale));
                }
                if (EF6MetadataHelpers.TryGetPrecision(edmType, out precision))
                {
                    return(TypeUsage.CreateDecimalTypeUsage(this.StoreTypeNameToStorePrimitiveType["number"], precision, (byte)0));
                }
                if (EF6MetadataHelpers.TryGetScale(edmType, out scale))
                {
                    return(TypeUsage.CreateDecimalTypeUsage(this.StoreTypeNameToStorePrimitiveType["number"], (byte)38, scale));
                }
                return(TypeUsage.CreateDefaultTypeUsage((EdmType)this.StoreTypeNameToStorePrimitiveType["number"]));

            case PrimitiveTypeKind.Double:
                if (this._version < EFOracleVersion.Oracle10gR1)
                {
                    return(TypeUsage.CreateDefaultTypeUsage((EdmType)this.StoreTypeNameToStorePrimitiveType["number"]));
                }
                return(TypeUsage.CreateDefaultTypeUsage((EdmType)this.StoreTypeNameToStorePrimitiveType["binary_double"]));

            case PrimitiveTypeKind.Guid:
                return(TypeUsage.CreateDefaultTypeUsage((EdmType)this.StoreTypeNameToStorePrimitiveType["guid raw"]));

            case PrimitiveTypeKind.Single:
                if (this._version < EFOracleVersion.Oracle10gR1)
                {
                    return(TypeUsage.CreateDefaultTypeUsage((EdmType)this.StoreTypeNameToStorePrimitiveType["number"]));
                }
                return(TypeUsage.CreateDefaultTypeUsage((EdmType)this.StoreTypeNameToStorePrimitiveType["binary_float"]));

            case PrimitiveTypeKind.Int16:
                return(TypeUsage.CreateDecimalTypeUsage(this.StoreTypeNameToStorePrimitiveType["number"], (byte)EFOracleProviderManifest.m_edmMappingMaxINT16, (byte)0));

            case PrimitiveTypeKind.Int32:
                return(TypeUsage.CreateDecimalTypeUsage(this.StoreTypeNameToStorePrimitiveType["number"], (byte)EFOracleProviderManifest.m_edmMappingMaxINT32, (byte)0));

            case PrimitiveTypeKind.Int64:
                return(TypeUsage.CreateDecimalTypeUsage(this.StoreTypeNameToStorePrimitiveType["number"], (byte)EFOracleProviderManifest.m_edmMappingMaxINT64, (byte)0));

            case PrimitiveTypeKind.String:
                bool  flag3      = facets["Unicode"].Value == null || (bool)facets["Unicode"].Value;
                bool  flag4      = facets["FixedLength"].Value != null && (bool)facets["FixedLength"].Value;
                Facet facet2     = facets["MaxLength"];
                bool  flag5      = !bUse32DataTypes ? facet2.IsUnbounded || facet2.Value == null || (int)facet2.Value > (flag3 ? 4000 : 4000) : facet2.IsUnbounded || facet2.Value == null || (int)facet2.Value > (flag3 ? this.Nvarchar2MaxSize_12c : this.Varchar2MaxSize_12c);
                int   maxLength2 = !flag5 ? (int)facet2.Value : int.MinValue;
                return(!flag3 ? (!flag4 ? (!flag5 ? TypeUsage.CreateStringTypeUsage(this.StoreTypeNameToStorePrimitiveType["varchar2"], false, false, maxLength2) : TypeUsage.CreateStringTypeUsage(this.StoreTypeNameToStorePrimitiveType["clob"], false, false)) : TypeUsage.CreateStringTypeUsage(this.StoreTypeNameToStorePrimitiveType["char"], false, true, flag5 ? 2000 : maxLength2)) : (!flag4 ? (!flag5 ? TypeUsage.CreateStringTypeUsage(this.StoreTypeNameToStorePrimitiveType["nvarchar2"], true, false, maxLength2) : TypeUsage.CreateStringTypeUsage(this.StoreTypeNameToStorePrimitiveType["nclob"], true, false)) : TypeUsage.CreateStringTypeUsage(this.StoreTypeNameToStorePrimitiveType["nchar"], true, true, flag5 ? 2000 : maxLength2)));

            case PrimitiveTypeKind.DateTimeOffset:
                return(TypeUsage.CreateDefaultTypeUsage((EdmType)this.StoreTypeNameToStorePrimitiveType["timestamp with time zone"]));

            default:
                throw new NotSupportedException(EFProviderSettings.Instance.GetErrorMessage(-1703, "Oracle Data Provider for .NET", edmType1.PrimitiveTypeKind.ToString()));
            }
        }
        private string GetFacetString(EdmProperty column, bool IsKeyMember)
        {
            StringBuilder sql = new StringBuilder();
            Facet         facet;
            Facet         fcDateTimePrecision = null;

            ReadOnlyMetadataCollection <Facet> facets = column.TypeUsage.Facets;

            if (column.TypeUsage.EdmType.BaseType.Name == "String")
            {
                // types tinytext, mediumtext, text & longtext don't have a length.
                if (!column.TypeUsage.EdmType.Name.EndsWith("text", StringComparison.OrdinalIgnoreCase))
                {
                    if (facets.TryGetValue("MaxLength", true, out facet))
                    {
                        sql.AppendFormat(" ({0})", facet.Value);
                    }
                }
            }
            else if (column.TypeUsage.EdmType.BaseType.Name == "Decimal")
            {
                Facet fcScale;
                Facet fcPrecision;
                if (facets.TryGetValue("Scale", true, out fcScale) && facets.TryGetValue("Precision", true, out fcPrecision))
                {
                    // Enforce scale to a reasonable value.
                    int scale = fcScale.Value == null ? 0 : ( int )( byte )fcScale.Value;
                    if (scale == 0)
                    {
                        scale = MySqlProviderManifest.DEFAULT_DECIMAL_SCALE;
                    }
                    sql.AppendFormat("( {0}, {1} ) ", fcPrecision.Value, scale);
                }
            }
            else if (column.TypeUsage.EdmType.BaseType.Name == "DateTime")
            {
                if (serverVersion >= new Version(5, 6) && facets.TryGetValue("Precision", true, out fcDateTimePrecision))
                {
                    if (Convert.ToByte(fcDateTimePrecision.Value) >= 1)
                    {
                        sql.AppendFormat("( {0} ) ", fcDateTimePrecision.Value);
                    }
                }
            }


            if (facets.TryGetValue("Nullable", true, out facet) && (bool)facet.Value == false)
            {
                sql.Append(" NOT NULL");
            }

            if (facets.TryGetValue("StoreGeneratedPattern", true, out facet))
            {
                if (facet.Value.Equals(StoreGeneratedPattern.Identity))
                {
                    if (column.TypeUsage.EdmType.BaseType.Name.StartsWith("Int"))
                    {
                        sql.Append(" AUTO_INCREMENT UNIQUE");
                    }
                    else if (column.TypeUsage.EdmType.BaseType.Name == "Guid")
                    {
                        _guidIdentityColumns.Add(column.Name);
                    }
                    else if (serverVersion >= new Version(5, 6) && column.TypeUsage.EdmType.BaseType.Name == "DateTime")
                    {
                        sql.AppendFormat(" DEFAULT CURRENT_TIMESTAMP{0}", fcDateTimePrecision != null && Convert.ToByte(fcDateTimePrecision.Value) >= 1 ? "( " + fcDateTimePrecision.Value.ToString() + " )" : "");
                    }
                    else
                    {
                        throw new MySqlException("Invalid identity column type.");
                    }
                }
                else if (facet.Value.Equals(StoreGeneratedPattern.Computed))
                {
                    if (serverVersion >= new Version(5, 6) && column.TypeUsage.EdmType.BaseType.Name == "DateTime")
                    {
                        sql.AppendFormat(" DEFAULT CURRENT_TIMESTAMP{0}", fcDateTimePrecision != null && Convert.ToByte(fcDateTimePrecision.Value) >= 1 ? "( " + fcDateTimePrecision.Value.ToString() + " )" : "");
                    }
                }
            }
            return(sql.ToString());
        }
            private static Mock<EntityType> CreateMockEntityType(params string[] keyNames)
            {
                var metadataCollection = new ReadOnlyMetadataCollection<EdmMember>(
                    keyNames.Select(
                        k =>
                        {
                            var mockEdmMember1 = new Mock<EdmMember>();
                            mockEdmMember1.Setup(m => m.Name).Returns(k);
                            return mockEdmMember1.Object;
                        }).ToList());

                var mockEntityType = new Mock<EntityType>();
                mockEntityType.Setup(m => m.KeyMembers).Returns(metadataCollection);
                mockEntityType.Setup(m => m.IsAssignableFrom(mockEntityType.Object)).Returns(true);
                mockEntityType.Setup(m => m.KeyMemberNames).Returns(keyNames.Select(k => k).ToArray());

                return mockEntityType;
            }
Beispiel #36
0
        internal void UpdateForeignKeyValues(
            IEntityWrapper dependentEntity,
            IEntityWrapper principalEntity,
            Dictionary <int, object> changedFKs,
            bool forceChange)
        {
            ReferentialConstraint referentialConstraint = ((AssociationType)this.RelationMetadata).ReferentialConstraints[0];
            bool flag = (object)this.WrappedOwner.EntityKey != null && !this.WrappedOwner.EntityKey.IsTemporary && this.IsDependentEndOfReferentialConstraint(true);
            ObjectStateManager objectStateManager = this.ObjectContext.ObjectStateManager;

            objectStateManager.TransactionManager.BeginForeignKeyUpdate(this);
            try
            {
                EntitySet entitySet1 = ((AssociationSet)this.RelationshipSet).AssociationSetEnds[this.ToEndMember.Name].EntitySet;
                StateManagerTypeMetadata managerTypeMetadata1 = objectStateManager.GetOrAddStateManagerTypeMetadata(principalEntity.IdentityType, entitySet1);
                EntitySet entitySet2 = ((AssociationSet)this.RelationshipSet).AssociationSetEnds[this.FromEndMember.Name].EntitySet;
                StateManagerTypeMetadata managerTypeMetadata2           = objectStateManager.GetOrAddStateManagerTypeMetadata(dependentEntity.IdentityType, entitySet2);
                ReadOnlyMetadataCollection <EdmProperty> fromProperties = referentialConstraint.FromProperties;
                int      count = fromProperties.Count;
                string[] array = (string[])null;
                object[] compositeKeyValues = (object[])null;
                if (count > 1)
                {
                    array = entitySet1.ElementType.KeyMemberNames;
                    compositeKeyValues = new object[count];
                }
                for (int index1 = 0; index1 < count; ++index1)
                {
                    int    olayerMemberName1 = managerTypeMetadata1.GetOrdinalforOLayerMemberName(fromProperties[index1].Name);
                    object obj = managerTypeMetadata1.Member(olayerMemberName1).GetValue(principalEntity.Entity);
                    int    olayerMemberName2       = managerTypeMetadata2.GetOrdinalforOLayerMemberName(referentialConstraint.ToProperties[index1].Name);
                    bool   changingForeignKeyValue = !ByValueEqualityComparer.Default.Equals(managerTypeMetadata2.Member(olayerMemberName2).GetValue(dependentEntity.Entity), obj);
                    if (forceChange || changingForeignKeyValue)
                    {
                        if (flag)
                        {
                            this.ValidateSettingRIConstraints(principalEntity, obj == null, changingForeignKeyValue);
                        }
                        if (changedFKs != null)
                        {
                            object x;
                            if (changedFKs.TryGetValue(olayerMemberName2, out x))
                            {
                                if (!ByValueEqualityComparer.Default.Equals(x, obj))
                                {
                                    throw new InvalidOperationException(Strings.Update_ReferentialConstraintIntegrityViolation);
                                }
                            }
                            else
                            {
                                changedFKs[olayerMemberName2] = obj;
                            }
                        }
                        dependentEntity.SetCurrentValue(dependentEntity.ObjectStateEntry, managerTypeMetadata2.Member(olayerMemberName2), -1, dependentEntity.Entity, obj);
                    }
                    if (count > 1)
                    {
                        int index2 = Array.IndexOf <string>(array, fromProperties[index1].Name);
                        compositeKeyValues[index2] = obj;
                    }
                    else
                    {
                        this.SetCachedForeignKey(obj == null ? (EntityKey)null : new EntityKey((EntitySetBase)entitySet1, obj), dependentEntity.ObjectStateEntry);
                    }
                }
                if (count > 1)
                {
                    this.SetCachedForeignKey(((IEnumerable <object>)compositeKeyValues).Any <object>((Func <object, bool>)(v => v == null)) ? (EntityKey)null : new EntityKey((EntitySetBase)entitySet1, compositeKeyValues), dependentEntity.ObjectStateEntry);
                }
                if (this.WrappedOwner.ObjectStateEntry == null)
                {
                    return;
                }
                objectStateManager.ForgetEntryWithConceptualNull(this.WrappedOwner.ObjectStateEntry, false);
            }
            finally
            {
                objectStateManager.TransactionManager.EndForeignKeyUpdate();
            }
        }
 /// <summary>
 /// Initializes a new instance of Entity Type
 /// </summary>
 /// <param name="name">name of the entity type</param>
 /// <param name="namespaceName">namespace of the entity type</param>
 /// <param name="version">version of the entity type</param>
 /// <param name="dataSpace">dataSpace in which this edmtype belongs to</param>
 /// <exception cref="System.ArgumentNullException">Thrown if either name, namespace or version arguments are null</exception>
 internal EntityTypeBase(string name, string namespaceName, DataSpace dataSpace)
     : base(name, namespaceName, dataSpace)
 {
     _keyMembers = new ReadOnlyMetadataCollection<EdmMember>(new MetadataCollection<EdmMember>());
 }
        public override TypeUsage GetStoreType(TypeUsage edmType)
        {
            if (edmType == null)
            {
                throw new ArgumentNullException("edmType");
            }

            Debug.Assert(edmType.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType);

            PrimitiveType primitiveType = edmType.EdmType as PrimitiveType;

            if (primitiveType == null)
            {
                throw new ArgumentException(String.Format(Resources.TypeNotSupported, edmType));
            }

            ReadOnlyMetadataCollection <Facet> facets = edmType.Facets;

            switch (primitiveType.PrimitiveTypeKind)
            {
            case PrimitiveTypeKind.Boolean:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bool"]));

            case PrimitiveTypeKind.Byte:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["utinyint"]));

            case PrimitiveTypeKind.SByte:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["tinyint"]));

            case PrimitiveTypeKind.Int16:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["smallint"]));

            case PrimitiveTypeKind.Int32:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["int"]));

            case PrimitiveTypeKind.Int64:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bigint"]));

            case PrimitiveTypeKind.Guid:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["guid"]));

            case PrimitiveTypeKind.Double:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["double"]));

            case PrimitiveTypeKind.Single:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["float"]));

            case PrimitiveTypeKind.Decimal:
            {
                byte  precision = DEFAULT_DECIMAL_PRECISION;
                byte  scale     = DEFAULT_DECIMAL_SCALE;
                Facet facet;

                if (edmType.Facets.TryGetValue("Precision", false, out facet))
                {
                    if (!facet.IsUnbounded && facet.Value != null)
                    {
                        precision = (byte)facet.Value;
                    }
                }

                if (edmType.Facets.TryGetValue("Scale", false, out facet))
                {
                    if (!facet.IsUnbounded && facet.Value != null)
                    {
                        scale = (byte)facet.Value;
                    }
                }

                return(TypeUsage.CreateDecimalTypeUsage(StoreTypeNameToStorePrimitiveType["decimal"], precision, scale));
            }

            case PrimitiveTypeKind.Binary:
            {
                bool  isFixedLength = null != facets["FixedLength"].Value && (bool)facets["FixedLength"].Value;
                Facet f             = facets["MaxLength"];
                bool  isMaxLength   = f.IsUnbounded || null == f.Value || (int)f.Value > MEDIUMBLOB_MAXLEN;
                int   maxLength     = !isMaxLength ? (int)f.Value : LONGBLOB_MAXLEN;

                string typeName = String.Empty;

                // now this applies for both isFixedLength and !isFixedLength
                if (maxLength < CHAR_MAXLEN)
                {
                    typeName = "tinyblob";
                }
                else if (maxLength < MEDIUMBLOB_MAXLEN)
                {
                    typeName = "blob";
                }
                else if (maxLength < LONGTEXT_MAXLEN)
                {
                    typeName = "mediumblob";
                }
                else
                {
                    typeName = "longblob";
                }

                return(TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType[typeName], isFixedLength, maxLength));
            }

            case PrimitiveTypeKind.String:
            {
                string typeName      = String.Empty;
                bool   isUnicode     = null != facets["Unicode"].Value && (bool)facets["Unicode"].Value;
                bool   isFixedLength = null != facets["FixedLength"].Value && (bool)facets["FixedLength"].Value;
                int    maxLenghtValue;

                Facet maxLengthFacet = facets["MaxLength"];
                if (isFixedLength)
                {
                    typeName = isUnicode ? "nchar" : "char";
                    if (maxLengthFacet.Value != null && Int32.TryParse(maxLengthFacet.Value.ToString(), out maxLenghtValue) && maxLenghtValue <= CHAR_MAXLEN)
                    {
                        return(TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType[typeName], isUnicode, isFixedLength, (int)maxLengthFacet.Value));
                    }
                    else if (maxLengthFacet.Value != null && maxLengthFacet.Value.ToString() == "Max")
                    {
                        return(TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType[typeName], isUnicode, isFixedLength, CHAR_MAXLEN));
                    }
                    else
                    {
                        return(TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType[typeName], isUnicode, isFixedLength));
                    }
                }
                else
                {
                    typeName = isUnicode ? "nvarchar" : "varchar";
                    if (maxLengthFacet.Value != null && Int32.TryParse(maxLengthFacet.Value.ToString(), out maxLenghtValue))
                    {
                        if (maxLenghtValue > VARCHAR_MAXLEN && maxLenghtValue <= MEDIUMTEXT_MAXLEN)
                        {
                            typeName = "mediumtext";
                        }
                        else if ((int)maxLengthFacet.Value > MEDIUMTEXT_MAXLEN)
                        {
                            typeName = "longtext";
                        }
                        return(TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType[typeName], isUnicode, isFixedLength, (int)maxLengthFacet.Value));
                    }
                    else if (maxLengthFacet.Value != null && (maxLengthFacet.Value.ToString() == "Max"))
                    {
                        return(TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["longtext"], isUnicode, isFixedLength));
                    }
                    else
                    {
                        return(TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType[typeName], isUnicode, isFixedLength));
                    }
                }
            }

            case PrimitiveTypeKind.DateTimeOffset:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["timestamp"]));

            case PrimitiveTypeKind.DateTime:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["datetime"]));

            case PrimitiveTypeKind.Time:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["time"]));

#if NET_45_OR_GREATER
            case PrimitiveTypeKind.Geometry:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["geometry"]));
#endif
            default:
                throw new NotSupportedException(String.Format(Resources.NoStoreTypeForEdmType, edmType, primitiveType.PrimitiveTypeKind));
            }
        }
        internal void ValidateEntityKey(
            MetadataWorkspace workspace,
            EntitySet entitySet,
            bool isArgumentException,
            string argumentName)
        {
            if (entitySet == null)
            {
                return;
            }
            ReadOnlyMetadataCollection <EdmMember> keyMembers = ((EntitySetBase)entitySet).ElementType.KeyMembers;

            if (this._singletonKeyValue != null)
            {
                if (keyMembers.Count != 1)
                {
                    if (isArgumentException)
                    {
                        throw new ArgumentException(Strings.EntityKey_IncorrectNumberOfKeyValuePairs((object)entitySet.ElementType.FullName, (object)keyMembers.Count, (object)1), argumentName);
                    }
                    throw new InvalidOperationException(Strings.EntityKey_IncorrectNumberOfKeyValuePairs((object)entitySet.ElementType.FullName, (object)keyMembers.Count, (object)1));
                }
                EntityKey.ValidateTypeOfKeyValue(workspace, keyMembers[0], this._singletonKeyValue, isArgumentException, argumentName);
                if (!(this._keyNames[0] != keyMembers[0].Name))
                {
                    return;
                }
                if (isArgumentException)
                {
                    throw new ArgumentException(Strings.EntityKey_MissingKeyValue((object)keyMembers[0].Name, (object)entitySet.ElementType.FullName), argumentName);
                }
                throw new InvalidOperationException(Strings.EntityKey_MissingKeyValue((object)keyMembers[0].Name, (object)entitySet.ElementType.FullName));
            }
            if (this._compositeKeyValues == null)
            {
                return;
            }
            if (keyMembers.Count != this._compositeKeyValues.Length)
            {
                if (isArgumentException)
                {
                    throw new ArgumentException(Strings.EntityKey_IncorrectNumberOfKeyValuePairs((object)entitySet.ElementType.FullName, (object)keyMembers.Count, (object)this._compositeKeyValues.Length), argumentName);
                }
                throw new InvalidOperationException(Strings.EntityKey_IncorrectNumberOfKeyValuePairs((object)entitySet.ElementType.FullName, (object)keyMembers.Count, (object)this._compositeKeyValues.Length));
            }
            for (int index1 = 0; index1 < this._compositeKeyValues.Length; ++index1)
            {
                EdmMember keyMember = ((EntitySetBase)entitySet).ElementType.KeyMembers[index1];
                bool      flag      = false;
                for (int index2 = 0; index2 < this._compositeKeyValues.Length; ++index2)
                {
                    if (keyMember.Name == this._keyNames[index2])
                    {
                        EntityKey.ValidateTypeOfKeyValue(workspace, keyMember, this._compositeKeyValues[index2], isArgumentException, argumentName);
                        flag = true;
                        break;
                    }
                }
                if (!flag)
                {
                    if (isArgumentException)
                    {
                        throw new ArgumentException(Strings.EntityKey_MissingKeyValue((object)keyMember.Name, (object)entitySet.ElementType.FullName), argumentName);
                    }
                    throw new InvalidOperationException(Strings.EntityKey_MissingKeyValue((object)keyMember.Name, (object)entitySet.ElementType.FullName));
                }
            }
        }
        /// <summary>
        /// This method takes a type and a set of facets and returns the best mapped equivalent type
        /// in Jet
        /// </summary>
        /// <param name="storeType">A TypeUsage encapsulating an EDM type and a set of facets</param>
        /// <returns>A TypeUsage encapsulating a store type and a set of facets</returns>
        public override TypeUsage GetStoreType(TypeUsage edmType)
        {
            if (edmType == null)
            {
                throw new ArgumentNullException("edmType");
            }

            System.Diagnostics.Debug.Assert(edmType.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType);

            PrimitiveType primitiveType = edmType.EdmType as PrimitiveType;

            if (primitiveType == null)
            {
                throw new ArgumentException(String.Format("The underlying provider does not support the type '{0}'.", edmType));
            }

            ReadOnlyMetadataCollection <Facet> facets = edmType.Facets;

            switch (primitiveType.PrimitiveTypeKind)
            {
            case PrimitiveTypeKind.Boolean:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bit"]));

            case PrimitiveTypeKind.Byte:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["tinyint"]));

            case PrimitiveTypeKind.Int16:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["smallint"]));

            case PrimitiveTypeKind.Int32:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["int"]));

            case PrimitiveTypeKind.Int64:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["int"]));

            case PrimitiveTypeKind.Guid:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["guid"]));

            case PrimitiveTypeKind.Double:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["float"]));

            case PrimitiveTypeKind.Single:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["real"]));

            case PrimitiveTypeKind.Decimal:     // decimal, numeric, smallmoney, money
            {
                byte precision;
                if (!edmType.TryGetPrecision(out precision))
                {
                    precision = 18;
                }

                byte scale;
                if (!edmType.TryGetScale(out scale))
                {
                    scale = 0;
                }

                return(TypeUsage.CreateDecimalTypeUsage(StoreTypeNameToStorePrimitiveType["decimal"], precision, scale));
            }

            case PrimitiveTypeKind.Binary:     // binary, varbinary, image
            {
                bool isFixedLength = edmType.GetIsFixedLength();
                bool isMaxLength   = edmType.GetMaxLength() > BINARY_MAXSIZE;
                int  maxLength     = edmType.GetMaxLength();

                TypeUsage tu;
                if (isFixedLength)
                {
                    tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["binary"], true, maxLength);
                }
                else if (isMaxLength)
                {
                    tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["image"], false);
                    System.Diagnostics.Debug.Assert(tu.Facets["MaxLength"].Description.IsConstant, "varbinary(max) is not constant!");
                }
                else
                {
                    tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["varbinary"], false, maxLength);
                }

                return(tu);
            }

            case PrimitiveTypeKind.String:
                // char, varchar, text
            {
                bool isUnicode     = edmType.GetIsUnicode();     // We do not handle unicode (everything's unicode in Jet)
                bool isFixedLength = edmType.GetIsFixedLength();
                bool isMaxLength   = edmType.GetMaxLength() > VARCHAR_MAXSIZE;
                int  maxLength     = edmType.GetMaxLength();

                TypeUsage tu;

                if (isFixedLength)
                {
                    tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["char"], false, true, maxLength);
                }
                else if (isMaxLength)
                {
                    tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["text"], false, false);
                }
                else
                {
                    tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["varchar"], false, false, maxLength);
                }

                return(tu);
            }

            case PrimitiveTypeKind.DateTime:     // datetime
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["datetime"]));

            case PrimitiveTypeKind.Time:     // time
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["time"]));

            default:
                throw new NotSupportedException(String.Format("There is no store type corresponding to the EDM type '{0}' of primitive type '{1}'.", edmType, primitiveType.PrimitiveTypeKind));
            }
        }
Beispiel #41
0
 private void ResetNavigationProperties(object sender, EventArgs e)
 {
     if (_navigationPropertiesCache != null)
     {
         lock (_navigationPropertiesCacheLock)
         {
             if (_navigationPropertiesCache != null)
             {
                 _navigationPropertiesCache = null;
                 Members.SourceAccessed -= ResetNavigationProperties;
             }
         }
     }
 }
Beispiel #42
0
        public override TypeUsage GetStoreType(TypeUsage edmType)
        {
            Check.NotNull <TypeUsage>(edmType, nameof(edmType));
            PrimitiveType edmType1 = edmType.EdmType as PrimitiveType;

            if (edmType1 == null)
            {
                throw new ArgumentException(Strings.ProviderDoesNotSupportType((object)edmType.EdmType.Name));
            }
            ReadOnlyMetadataCollection <Facet> facets = edmType.Facets;

            switch (edmType1.PrimitiveTypeKind)
            {
            case PrimitiveTypeKind.Binary:
                bool  flag1      = facets["FixedLength"].Value != null && (bool)facets["FixedLength"].Value;
                Facet facet1     = facets["MaxLength"];
                bool  flag2      = facet1.IsUnbounded || facet1.Value == null || (int)facet1.Value > 8000;
                int   maxLength1 = !flag2 ? (int)facet1.Value : int.MinValue;
                return(!flag1 ? (!flag2 ? TypeUsage.CreateBinaryTypeUsage(this.StoreTypeNameToStorePrimitiveType["varbinary"], false, maxLength1) : (this._version == SqlVersion.Sql8 ? TypeUsage.CreateBinaryTypeUsage(this.StoreTypeNameToStorePrimitiveType["varbinary"], false, 8000) : TypeUsage.CreateBinaryTypeUsage(this.StoreTypeNameToStorePrimitiveType["varbinary(max)"], false))) : TypeUsage.CreateBinaryTypeUsage(this.StoreTypeNameToStorePrimitiveType["binary"], true, flag2 ? 8000 : maxLength1));

            case PrimitiveTypeKind.Boolean:
                return(TypeUsage.CreateDefaultTypeUsage((EdmType)this.StoreTypeNameToStorePrimitiveType["bit"]));

            case PrimitiveTypeKind.Byte:
                return(TypeUsage.CreateDefaultTypeUsage((EdmType)this.StoreTypeNameToStorePrimitiveType["tinyint"]));

            case PrimitiveTypeKind.DateTime:
                return(TypeUsage.CreateDefaultTypeUsage((EdmType)this.StoreTypeNameToStorePrimitiveType["datetime"]));

            case PrimitiveTypeKind.Decimal:
                byte precision;
                if (!edmType.TryGetPrecision(out precision))
                {
                    precision = (byte)18;
                }
                byte scale;
                if (!edmType.TryGetScale(out scale))
                {
                    scale = (byte)0;
                }
                return(TypeUsage.CreateDecimalTypeUsage(this.StoreTypeNameToStorePrimitiveType["decimal"], precision, scale));

            case PrimitiveTypeKind.Double:
                return(TypeUsage.CreateDefaultTypeUsage((EdmType)this.StoreTypeNameToStorePrimitiveType["float"]));

            case PrimitiveTypeKind.Guid:
                return(TypeUsage.CreateDefaultTypeUsage((EdmType)this.StoreTypeNameToStorePrimitiveType["uniqueidentifier"]));

            case PrimitiveTypeKind.Single:
                return(TypeUsage.CreateDefaultTypeUsage((EdmType)this.StoreTypeNameToStorePrimitiveType["real"]));

            case PrimitiveTypeKind.Int16:
                return(TypeUsage.CreateDefaultTypeUsage((EdmType)this.StoreTypeNameToStorePrimitiveType["smallint"]));

            case PrimitiveTypeKind.Int32:
                return(TypeUsage.CreateDefaultTypeUsage((EdmType)this.StoreTypeNameToStorePrimitiveType["int"]));

            case PrimitiveTypeKind.Int64:
                return(TypeUsage.CreateDefaultTypeUsage((EdmType)this.StoreTypeNameToStorePrimitiveType["bigint"]));

            case PrimitiveTypeKind.String:
                bool  flag3      = facets["Unicode"].Value == null || (bool)facets["Unicode"].Value;
                bool  flag4      = facets["FixedLength"].Value != null && (bool)facets["FixedLength"].Value;
                Facet facet2     = facets["MaxLength"];
                bool  flag5      = facet2.IsUnbounded || facet2.Value == null || (int)facet2.Value > (flag3 ? 4000 : 8000);
                int   maxLength2 = !flag5 ? (int)facet2.Value : int.MinValue;
                return(!flag3 ? (!flag4 ? (!flag5 ? TypeUsage.CreateStringTypeUsage(this.StoreTypeNameToStorePrimitiveType["varchar"], false, false, maxLength2) : (this._version == SqlVersion.Sql8 ? TypeUsage.CreateStringTypeUsage(this.StoreTypeNameToStorePrimitiveType["varchar"], false, false, 8000) : TypeUsage.CreateStringTypeUsage(this.StoreTypeNameToStorePrimitiveType["varchar(max)"], false, false))) : TypeUsage.CreateStringTypeUsage(this.StoreTypeNameToStorePrimitiveType["char"], false, true, flag5 ? 8000 : maxLength2)) : (!flag4 ? (!flag5 ? TypeUsage.CreateStringTypeUsage(this.StoreTypeNameToStorePrimitiveType["nvarchar"], true, false, maxLength2) : (this._version == SqlVersion.Sql8 ? TypeUsage.CreateStringTypeUsage(this.StoreTypeNameToStorePrimitiveType["nvarchar"], true, false, 4000) : TypeUsage.CreateStringTypeUsage(this.StoreTypeNameToStorePrimitiveType["nvarchar(max)"], true, false))) : TypeUsage.CreateStringTypeUsage(this.StoreTypeNameToStorePrimitiveType["nchar"], true, true, flag5 ? 4000 : maxLength2)));

            case PrimitiveTypeKind.Time:
                return(this.GetStorePrimitiveTypeIfPostSql9("time", edmType.EdmType.Name, edmType1.PrimitiveTypeKind));

            case PrimitiveTypeKind.DateTimeOffset:
                return(this.GetStorePrimitiveTypeIfPostSql9("datetimeoffset", edmType.EdmType.Name, edmType1.PrimitiveTypeKind));

            case PrimitiveTypeKind.Geometry:
            case PrimitiveTypeKind.GeometryPoint:
            case PrimitiveTypeKind.GeometryLineString:
            case PrimitiveTypeKind.GeometryPolygon:
            case PrimitiveTypeKind.GeometryMultiPoint:
            case PrimitiveTypeKind.GeometryMultiLineString:
            case PrimitiveTypeKind.GeometryMultiPolygon:
            case PrimitiveTypeKind.GeometryCollection:
                return(this.GetStorePrimitiveTypeIfPostSql9("geometry", edmType.EdmType.Name, edmType1.PrimitiveTypeKind));

            case PrimitiveTypeKind.Geography:
            case PrimitiveTypeKind.GeographyPoint:
            case PrimitiveTypeKind.GeographyLineString:
            case PrimitiveTypeKind.GeographyPolygon:
            case PrimitiveTypeKind.GeographyMultiPoint:
            case PrimitiveTypeKind.GeographyMultiLineString:
            case PrimitiveTypeKind.GeographyMultiPolygon:
            case PrimitiveTypeKind.GeographyCollection:
                return(this.GetStorePrimitiveTypeIfPostSql9("geography", edmType.EdmType.Name, edmType1.PrimitiveTypeKind));

            default:
                throw new NotSupportedException(Strings.NoStoreTypeForEdmType((object)edmType.EdmType.Name, (object)edmType1.PrimitiveTypeKind));
            }
        }
            public void GetProperties_returns_row_type_properties()
            {
                var properties = new ReadOnlyMetadataCollection<EdmProperty>();

                var mockEdmType = new Mock<RowType>();
                mockEdmType.Setup(m => m.BuiltInTypeKind).Returns(BuiltInTypeKind.RowType);
                mockEdmType.Setup(m => m.Properties).Returns(properties);

                Assert.Same(properties, TypeUsage.Create(mockEdmType.Object).GetProperties());
            }
Beispiel #44
0
 internal NextResultGenerator(ObjectContext context, EntityCommand entityCommand, EdmType[] edmTypes, ReadOnlyMetadataCollection <EntitySet> entitySets, MergeOption mergeOption, int resultSetIndex)
 {
     _context        = context;
     _entityCommand  = entityCommand;
     _entitySets     = entitySets;
     _edmTypes       = edmTypes;
     _resultSetIndex = resultSetIndex;
     _mergeOption    = mergeOption;
 }
        private IEnumerable<DynamicFilterDefinition> FindFiltersForEntitySet(ReadOnlyMetadataCollection<MetadataProperty> metadataProperties, EntityContainer entityContainer)
        {
            var filterList = metadataProperties
                .Where(mp => mp.Name.Contains("customannotation:" + DynamicFilterConstants.ATTRIBUTE_NAME_PREFIX))
                .Select(m => m.Value as DynamicFilterDefinition)
                .ToList();

            //  Note: Prior to the switch to use CSpace (which was done to allow filters on navigation properties),
            //  we had to remove filters that exist in base EntitySets to this entity to fix issues with 
            //  Table-per-Type inheritance (issue #32).  In CSpace none of that is necessary since we are working
            //  with the actual c# models now (in CSpace) so we always have the correct filters and access to all
            //  the inherited properties that we need.
            if (filterList.Any())
            {
                //  Recursively remove any filters that exist in base EntitySets to this entity.
                //  This happens when an entity uses Table-per-Type inheritance.  Filters will be added
                //  to all derived EntitySets because of the inheritance in the C# classes.  But the database
                //  representation (the EntitySet) does not give access to inherited propeties since they
                //  only exist in the child EntitySet.  And on queries of entities involved in TPT, the
                //  query will generate a DbScanExpression for each EntitySet - so we only want the filters
                //  applied to the DbScanExpression to which they apply.
                //  See issue #32.
                RemoveFiltersForBaseClass(filterList.First().CLRType, filterList, entityContainer);
            }

            return filterList;
        }
Beispiel #46
0
    /// <summary>
    /// This method attempts to determine if the specified table has an integer
    /// primary key (i.e. "rowid").  If so, it sets the
    /// <paramref name="primaryKeyMember" /> parameter to the right
    /// <see cref="EdmMember" />; otherwise, the
    /// <paramref name="primaryKeyMember" /> parameter is set to null.
    /// </summary>
    /// <param name="table">The table to check.</param>
    /// <param name="keyMembers">
    /// The collection of key members.  An attempt is always made to set this
    /// parameter to a valid value.
    /// </param>
    /// <param name="primaryKeyMember">
    /// The <see cref="EdmMember" /> that represents the integer primary key
    /// -OR- null if no such <see cref="EdmMember" /> exists.
    /// </param>
    /// <returns>
    /// Non-zero if the specified table has an integer primary key.
    /// </returns>
    private static bool IsIntegerPrimaryKey(
        EntitySetBase table,
        out ReadOnlyMetadataCollection<EdmMember> keyMembers,
        out EdmMember primaryKeyMember
        )
    {
        keyMembers = table.ElementType.KeyMembers;

        if (keyMembers.Count == 1) /* NOTE: The "rowid" only? */
        {
            EdmMember keyMember = keyMembers[0];
            PrimitiveTypeKind typeKind;

            if (MetadataHelpers.TryGetPrimitiveTypeKind(
                    keyMember.TypeUsage, out typeKind) &&
                (typeKind == PrimitiveTypeKind.Int64))
            {
                primaryKeyMember = keyMember;
                return true;
            }
        }

        primaryKeyMember = null;
        return false;
    }
Beispiel #47
0
    /// <summary>
    /// This method attempts to determine if all the specified key members have
    /// values available.
    /// </summary>
    /// <param name="translator">
    /// The <see cref="ExpressionTranslator" /> to use.
    /// </param>
    /// <param name="keyMembers">
    /// The collection of key members to check.
    /// </param>
    /// <param name="missingKeyMember">
    /// The first missing key member that is found.  This is only set to a valid
    /// value if the method is returning false.
    /// </param>
    /// <returns>
    /// Non-zero if all key members have values; otherwise, zero.
    /// </returns>
    private static bool DoAllKeyMembersHaveValues(
        ExpressionTranslator translator,
        ReadOnlyMetadataCollection<EdmMember> keyMembers,
        out EdmMember missingKeyMember
        )
    {
        foreach (EdmMember keyMember in keyMembers)
        {
            if (!translator.MemberValues.ContainsKey(keyMember))
            {
                missingKeyMember = keyMember;
                return false;
            }
        }

        missingKeyMember = null;
        return true;
    }
 //Return a set of integers that represent the indexes of first set of properties in the second set
 private static Set<int> GetPropertyIndexes(
     IEnumerable<EdmProperty> properties1, ReadOnlyMetadataCollection<EdmProperty> properties2)
 {
     var propertyIndexes = new Set<int>();
     foreach (var prop in properties1)
     {
         propertyIndexes.Add(properties2.IndexOf(prop));
     }
     return propertyIndexes;
 }
        /// <summary>
        /// This method takes a type and a set of facets and returns the best mapped equivalent type
        /// in Ingres, taking the store version into consideration.
        /// </summary>
        /// <param name="storeType">A TypeUsage encapsulating an EDM type and a set of facets</param>
        /// <returns>A TypeUsage encapsulating a store type and a set of facets</returns>
        public override TypeUsage GetStoreType(TypeUsage edmType)
        {
            if (edmType == null)
            {
                throw new ArgumentNullException("edmType");
            }
            Debug.Assert(edmType.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType);

            var primitiveType = edmType.EdmType as PrimitiveType;

            if (primitiveType == null)
            {
                throw new ArgumentException(String.Format("The underlying provider does not support the type '{0}'.", edmType));
            }

            ReadOnlyMetadataCollection <Facet> facets = edmType.Facets;

            switch (primitiveType.PrimitiveTypeKind)
            {
            case PrimitiveTypeKind.Boolean:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["tinyint"]));

            case PrimitiveTypeKind.SByte:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["tinyint"]));

            case PrimitiveTypeKind.Byte:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["smallint"]));

            case PrimitiveTypeKind.Int16:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["smallint"]));

            case PrimitiveTypeKind.Int32:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["integer"]));

            case PrimitiveTypeKind.Int64:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bigint"]));

            case PrimitiveTypeKind.Double:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["float"]));

            case PrimitiveTypeKind.Single:
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["real"]));

            case PrimitiveTypeKind.Decimal:     // decimal, money
                return(TypeUsage.CreateDecimalTypeUsage(StoreTypeNameToStorePrimitiveType["decimal"], TypeHelpers.GetPrecision(edmType, 18), TypeHelpers.GetScale(edmType, 0)));

            case PrimitiveTypeKind.Binary:     // byte, byte varying, long byte
            {
                var isFixedLength  = facets["FixedLength"].GetValue <bool>(false);
                var maxLengthFacet = facets["MaxLength"];
                var maxLength      = maxLengthFacet.GetValue <int?>();
                if (maxLengthFacet.IsUnbounded || maxLength == null || maxLength.Value > binaryMaxSize)
                {
                    maxLength = null;
                }

                var storeTypeName = isFixedLength ? "byte" : maxLength == null ? "long byte" : "byte varying";

                return(CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType[storeTypeName], isFixedLength, maxLength));
            }

            case PrimitiveTypeKind.String:     // char, nchar, varchar, nvarchar, long varchar, long nvarchar
            {
                var isUnicode      = facets["Unicode"].GetValue <bool>(false);
                var isFixedLength  = facets["FixedLength"].GetValue <bool>(false);
                var maxLengthFacet = facets["MaxLength"];
                var maxLength      = maxLengthFacet.GetValue <int?>();
                if (maxLengthFacet.IsUnbounded || maxLength == null || maxLength.Value > varcharMaxSize)
                {
                    maxLength = null;
                }

                var storeTypeName = isFixedLength ? "char" : "varchar";
                storeTypeName = isUnicode ? "n" + storeTypeName : storeTypeName;
                storeTypeName = (maxLength == null) ? "long " + storeTypeName : storeTypeName;

                return(CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType[storeTypeName], isUnicode, isFixedLength, maxLength));
            }

            case PrimitiveTypeKind.DateTime:     // ingresdate
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["ingresdate"]));

            case PrimitiveTypeKind.Time:     // time
                return(TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["time"]));

            default:
                throw new NotSupportedException(String.Format("There is no store type corresponding to the EDM type '{0}' of primitive type '{1}'.", edmType, primitiveType.PrimitiveTypeKind));
            }
        }