public static void SetDefaultDiscriminator(
            this MappingFragment entityTypeMappingFragment, EdmProperty discriminator)
        {
            DebugCheck.NotNull(entityTypeMappingFragment);

            entityTypeMappingFragment.Annotations.SetAnnotation(DefaultDiscriminatorAnnotation, discriminator);
        }
        public static EdmProperty IncludeColumn(
            EntityType table, EdmProperty templateColumn, Func<EdmProperty, bool> isCompatible, bool useExisting)
        {
            DebugCheck.NotNull(table);
            DebugCheck.NotNull(templateColumn);

            var existingColumn = table.Properties.FirstOrDefault(isCompatible);

            if (existingColumn == null)
            {
                templateColumn = templateColumn.Clone();
            }
            else if (!useExisting
                     && !existingColumn.IsPrimaryKeyColumn)
            {
                templateColumn = templateColumn.Clone();
            }
            else
            {
                templateColumn = existingColumn;
            }

            AddColumn(table, templateColumn);

            return templateColumn;
        }
        public override IConfiguration Discover(EdmProperty property, DbModel model)
        {
            Debug.Assert(property != null, "property is null.");
            Debug.Assert(model != null, "model is null.");

            if (!_lengthTypes.Contains(property.PrimitiveType.PrimitiveTypeKind))
            {
                // Doesn't apply
                return null;
            }

            if (property.IsMaxLength
                || !property.MaxLength.HasValue
                || (property.MaxLength.Value == 128 && property.IsKey()))
            {
                // By convention
                return null;
            }

            var configuration = property.PrimitiveType.PrimitiveTypeKind == PrimitiveTypeKind.String
                ? new MaxLengthStringConfiguration()
                : new MaxLengthConfiguration();
            configuration.MaxLength = property.MaxLength.Value;

            return configuration;
        }
        public void Can_generate_scalar_and_complex_properties_when_update()
        {
            var functionParameterMappingGenerator
                = new FunctionParameterMappingGenerator(ProviderRegistry.Sql2008_ProviderManifest);

            var property0 = new EdmProperty("P0");
            var property1 = new EdmProperty("P1");
            var property2 = new EdmProperty("P2");

            property2.SetStoreGeneratedPattern(StoreGeneratedPattern.Computed);
            property2.ConcurrencyMode = ConcurrencyMode.Fixed;

            var complexType = new ComplexType("CT", "N", DataSpace.CSpace);

            complexType.AddMember(property1);

            var complexProperty = EdmProperty.CreateComplex("C", complexType);

            var parameterBindings
                = functionParameterMappingGenerator
                    .Generate(
                        ModificationOperator.Update,
                        new[] { property0, complexProperty, property2 },
                        new[]
                            {
                                new ColumnMappingBuilder(new EdmProperty("C0"), new[] { property0 }),
                                new ColumnMappingBuilder(new EdmProperty("C_P1"), new[] { complexProperty, property1 }),
                                new ColumnMappingBuilder(new EdmProperty("C2"), new[] { property2 })
                            },
                        new List<EdmProperty>(),
                        useOriginalValues: true)
                    .ToList();

            Assert.Equal(3, parameterBindings.Count());

            var parameterBinding = parameterBindings.First();

            Assert.Equal("C0", parameterBinding.Parameter.Name);
            Assert.Same(property0, parameterBinding.MemberPath.Members.Single());
            Assert.Equal("String", parameterBinding.Parameter.TypeName);
            Assert.Equal(ParameterMode.In, parameterBinding.Parameter.Mode);
            Assert.False(parameterBinding.IsCurrent);

            parameterBinding = parameterBindings.ElementAt(1);

            Assert.Equal("C_P1", parameterBinding.Parameter.Name);
            Assert.Same(complexProperty, parameterBinding.MemberPath.Members.First());
            Assert.Same(property1, parameterBinding.MemberPath.Members.Last());
            Assert.Equal("String", parameterBinding.Parameter.TypeName);
            Assert.Equal(ParameterMode.In, parameterBinding.Parameter.Mode);
            Assert.False(parameterBinding.IsCurrent);

            parameterBinding = parameterBindings.Last();

            Assert.Equal("C2_Original", parameterBinding.Parameter.Name);
            Assert.Same(property2, parameterBinding.MemberPath.Members.Single());
            Assert.Equal("String", parameterBinding.Parameter.TypeName);
            Assert.Equal(ParameterMode.In, parameterBinding.Parameter.Mode);
            Assert.False(parameterBinding.IsCurrent);
        }
        public static EdmProperty IncludeColumn(
            EntityType table, EdmProperty templateColumn, bool useExisting)
        {
            DebugCheck.NotNull(table);
            DebugCheck.NotNull(templateColumn);

            var existingColumn =
                table.Properties.SingleOrDefault(c => string.Equals(c.Name, templateColumn.Name, StringComparison.Ordinal));

            if (existingColumn == null)
            {
                templateColumn = templateColumn.Clone();
            }
            else if (!useExisting
                     && !existingColumn.IsPrimaryKeyColumn)
            {
                templateColumn = templateColumn.Clone();
            }
            else
            {
                templateColumn = existingColumn;
            }

            AddColumn(table, templateColumn);

            return templateColumn;
        }
        internal FunctionImportMappingComposable(
            EdmFunction functionImport,
            EdmFunction targetFunction,
            List<Tuple<StructuralType, List<StorageConditionPropertyMapping>, List<StoragePropertyMapping>>> structuralTypeMappings,
            EdmProperty[] targetFunctionKeys,
            StorageMappingItemCollection mappingItemCollection)
            : base(functionImport, targetFunction)
        {
            DebugCheck.NotNull(mappingItemCollection);
            Debug.Assert(functionImport.IsComposableAttribute, "functionImport.IsComposableAttribute");
            Debug.Assert(targetFunction.IsComposableAttribute, "targetFunction.IsComposableAttribute");
            Debug.Assert(
                functionImport.EntitySet == null || structuralTypeMappings != null,
                "Function import returning entities must have structuralTypeMappings.");
            Debug.Assert(
                structuralTypeMappings == null || structuralTypeMappings.Count > 0, "Non-null structuralTypeMappings must not be empty.");
            EdmType resultType;
            Debug.Assert(
                structuralTypeMappings != null ||
                MetadataHelper.TryGetFunctionImportReturnType(functionImport, 0, out resultType) && TypeSemantics.IsScalarType(resultType),
                "Either type mappings should be specified or the function import should be Collection(Scalar).");
            Debug.Assert(
                functionImport.EntitySet == null || targetFunctionKeys != null,
                "Keys must be inferred for a function import returning entities.");
            Debug.Assert(targetFunctionKeys == null || targetFunctionKeys.Length > 0, "Keys must be null or non-empty.");

            m_mappingItemCollection = mappingItemCollection;
            // We will use these parameters to target s-space function calls in the generated command tree. 
            // Since enums don't exist in s-space we need to use the underlying type.
            m_commandParameters =
                functionImport.Parameters.Select(p => TypeHelpers.GetPrimitiveTypeUsageForScalar(p.TypeUsage).Parameter(p.Name)).ToArray();
            m_structuralTypeMappings = structuralTypeMappings;
            m_targetFunctionKeys = targetFunctionKeys;
        }
        internal ConditionPropertyMapping(EdmProperty propertyOrColumn, object value, bool? isNull)
        {
            DebugCheck.NotNull(propertyOrColumn);
            Debug.Assert((isNull.HasValue) || (value != null), "Either Value or IsNull has to be specified on Condition Mapping");
            Debug.Assert(!(isNull.HasValue) || (value == null), "Both Value and IsNull can not be specified on Condition Mapping");

            var dataSpace = propertyOrColumn.TypeUsage.EdmType.DataSpace;

            switch (dataSpace)
            {
                case DataSpace.CSpace:
                    base.Property = propertyOrColumn;
                    break;

                case DataSpace.SSpace:
                    _column = propertyOrColumn;
                    break;

                default:
                    throw new ArgumentException(
                        Strings.MetadataItem_InvalidDataSpace(dataSpace, typeof(EdmProperty).Name),
                        "propertyOrColumn");
            }

            _value = value;
            _isNull = isNull;
        }
        public IConfiguration Discover(EdmProperty property, DbModel model)
        {
            Debug.Assert(property != null, "property is null.");
            Debug.Assert(model != null, "model is null.");

            if (!_precisionTypes.Contains(property.PrimitiveType.PrimitiveTypeKind))
            {
                // Doesn't apply
                return null;
            }

            var storeProperty = model.GetColumn(property);
            var defaultPrecision = (byte)storeProperty.PrimitiveType.FacetDescriptions
                .First(d => d.FacetName == DbProviderManifest.PrecisionFacetName).DefaultValue;

            // NOTE: This facet is not propagated to the conceptual side of the reverse
            //       engineered model.
            var precision = storeProperty.Precision ?? defaultPrecision;

            if (precision == defaultPrecision)
            {
                // By convention
                return null;
            }

            return new PrecisionDateTimeConfiguration { Precision = precision };
        }
        public IConfiguration Discover(EdmProperty property, DbModel model)
        {
            Debug.Assert(property != null, "property is null.");
            Debug.Assert(model != null, "model is null.");

            var columnProperty = model.GetColumn(property);

            if (property.IsKey() && _identityKeyTypes.Contains(property.PrimitiveType.PrimitiveTypeKind))
            {
                if (columnProperty.IsStoreGeneratedIdentity)
                {
                    // By convention
                    return null;
                }
            }
            else if (columnProperty.IsTimestamp())
            {
                // By convention
                return null;
            }
            else if (columnProperty.StoreGeneratedPattern == StoreGeneratedPattern.None)
            {
                // Doesn't apply
                return null;
            }

            return new DatabaseGeneratedConfiguration { StoreGeneratedPattern = columnProperty.StoreGeneratedPattern };
        }
        public void Can_get_flattened_properties_for_nested_mapping()
        {
            var mappingFragment
                = new MappingFragment(
                    new EntitySet(),
                    new EntityTypeMapping(
                        new EntitySetMapping(
                            new EntitySet(),
                            new EntityContainerMapping(new EntityContainer("C", DataSpace.CSpace)))), false);

            Assert.Empty(mappingFragment.ColumnMappings);

            var columnProperty = new EdmProperty("C", TypeUsage.Create(new PrimitiveType() { DataSpace = DataSpace.SSpace }));
            var property1 = EdmProperty.CreateComplex("P1", new ComplexType("CT"));
            var property2 = new EdmProperty("P2");

            var columnMappingBuilder1 = new ColumnMappingBuilder(columnProperty, new[] { property1, property2 });

            mappingFragment.AddColumnMapping(columnMappingBuilder1);

            var columnMappingBuilder2 = new ColumnMappingBuilder(columnProperty, new[] { property2 });

            mappingFragment.AddColumnMapping(columnMappingBuilder2);

            var columnMappingBuilders = mappingFragment.FlattenedProperties.ToList();

            Assert.Equal(2, columnMappingBuilders.Count());
            Assert.True(columnMappingBuilder1.PropertyPath.SequenceEqual(columnMappingBuilders.First().PropertyPath));
            Assert.True(columnMappingBuilder2.PropertyPath.SequenceEqual(columnMappingBuilders.Last().PropertyPath));
        }
        internal static void MapPrimitivePropertyFacets(
            EdmProperty property, EdmProperty column, TypeUsage typeUsage)
        {
            DebugCheck.NotNull(property);
            DebugCheck.NotNull(column);
            DebugCheck.NotNull(typeUsage);

            if (IsValidFacet(typeUsage, XmlConstants.FixedLengthElement))
            {
                column.IsFixedLength = property.IsFixedLength;
            }

            if (IsValidFacet(typeUsage, XmlConstants.MaxLengthElement))
            {
                column.IsMaxLength = property.IsMaxLength;
                column.MaxLength = property.MaxLength;
            }

            if (IsValidFacet(typeUsage, XmlConstants.UnicodeElement))
            {
                column.IsUnicode = property.IsUnicode;
            }

            if (IsValidFacet(typeUsage, XmlConstants.PrecisionElement))
            {
                column.Precision = property.Precision;
            }

            if (IsValidFacet(typeUsage, XmlConstants.ScaleElement))
            {
                column.Scale = property.Scale;
            }
        }
        protected EdmProperty MapTableColumn(
            EdmProperty property,
            string columnName,
            bool isInstancePropertyOnDerivedType)
        {
            DebugCheck.NotNull(property);
            DebugCheck.NotEmpty(columnName);

            var underlyingTypeUsage
                = TypeUsage.Create(property.UnderlyingPrimitiveType, property.TypeUsage.Facets);

            var storeTypeUsage = _providerManifest.GetStoreType(underlyingTypeUsage);

            var tableColumnMetadata
                = new EdmProperty(columnName, storeTypeUsage)
                      {
                          Nullable = isInstancePropertyOnDerivedType || property.Nullable
                      };

            if (tableColumnMetadata.IsPrimaryKeyColumn)
            {
                tableColumnMetadata.Nullable = false;
            }

            var storeGeneratedPattern = property.GetStoreGeneratedPattern();

            if (storeGeneratedPattern != null)
            {
                tableColumnMetadata.StoreGeneratedPattern = storeGeneratedPattern.Value;
            }

            MapPrimitivePropertyFacets(property, tableColumnMetadata, storeTypeUsage);

            return tableColumnMetadata;
        }
        /// <inheritdoc/>
        protected override bool MatchDependentKeyProperty(
            AssociationType associationType,
            AssociationEndMember dependentAssociationEnd,
            EdmProperty dependentProperty,
            EntityType principalEntityType,
            EdmProperty principalKeyProperty)
        {
            Check.NotNull(associationType, "associationType");
            Check.NotNull(dependentAssociationEnd, "dependentAssociationEnd");
            Check.NotNull(dependentProperty, "dependentProperty");
            Check.NotNull(principalEntityType, "principalEntityType");
            Check.NotNull(principalKeyProperty, "principalKeyProperty");

            var otherEnd = associationType.GetOtherEnd(dependentAssociationEnd);

            var navigationProperty
                = dependentAssociationEnd.GetEntityType().NavigationProperties
                                         .SingleOrDefault(n => n.ResultEnd == otherEnd);

            if (navigationProperty == null)
            {
                return false;
            }

            return string.Equals(
                dependentProperty.Name, navigationProperty.Name + principalKeyProperty.Name,
                StringComparison.OrdinalIgnoreCase);
        }
        private void BuildColumnMapping(string identity, EdmProperty property, string propertyName, ColumnMapping columnMapping)
        {
            if (_primaryKeysMapping[identity].Contains(propertyName))
              {
            columnMapping.IsPk = true;
              }

              foreach (var facet in property.TypeUsage.Facets)
              {
            switch (facet.Name)
            {
              case "Nullable":
            columnMapping.Nullable = (bool)facet.Value;
            break;
              case "DefaultValue":
            columnMapping.DefaultValue = facet.Value;
            break;
              case "StoreGeneratedPattern":
            columnMapping.IsIdentity = (StoreGeneratedPattern)facet.Value == StoreGeneratedPattern.Identity;
            columnMapping.Computed = (StoreGeneratedPattern)facet.Value == StoreGeneratedPattern.Computed;
            break;
              case "MaxLength":
            columnMapping.MaxLength = (int)facet.Value;
            break;
            }
              }
        }
        public void EdmModel_NameIsTooLong_not_triggered_for_row_and_collection_types()
        {
            var intType = PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32);

            var properties = new EdmProperty[100];
            for (int i = 0; i < 100; i++)
            {
                properties[i] = EdmProperty.Primitive("Property" + i, intType);
            }

            var rowType = new RowType(properties);

            foreach (var type in new EdmType[] { rowType, rowType.GetCollectionType() })
            {
                var validationContext
                    = new EdmModelValidationContext(new EdmModel(DataSpace.SSpace), true);
                DataModelErrorEventArgs errorEventArgs = null;
                validationContext.OnError += (_, e) => errorEventArgs = e;

                EdmModelSyntacticValidationRules
                    .EdmModel_NameIsTooLong
                    .Evaluate(validationContext, type);

                Assert.Null(errorEventArgs);
            }
        }
        public void Configure_should_rename_columns_when_right_keys_configured()
        {
            var database = new EdmModel(DataSpace.CSpace);

            var associationSetMapping
                = new StorageAssociationSetMapping(
                    new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)),
                    new EntitySet())
                    .Initialize();

            var column = new EdmProperty("C");

            associationSetMapping.TargetEndMapping.AddProperty(new StorageScalarPropertyMapping(new EdmProperty("PK"), column));

            var manyToManyAssociationMappingConfiguration
                = new ManyToManyAssociationMappingConfiguration();

            manyToManyAssociationMappingConfiguration.MapRightKey("NewName");

            var mockPropertyInfo = new MockPropertyInfo();

            associationSetMapping.SourceEndMapping.EndMember = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace));
            associationSetMapping.SourceEndMapping.EndMember.SetClrPropertyInfo(mockPropertyInfo);

            manyToManyAssociationMappingConfiguration.Configure(associationSetMapping, database, mockPropertyInfo);

            Assert.Equal("NewName", column.Name);
        }
        internal override TypeUsage GetTypeUsage()
        {
            if (_typeUsage == null)
            {
                var listOfProperties = new List<EdmProperty>();
                foreach (var property in _properties)
                {
                    var edmProperty = new EdmProperty(property.FQName, property.GetTypeUsage());
                    edmProperty.AddMetadataProperties(property.OtherContent);
                    //edmProperty.DeclaringType
                    listOfProperties.Add(edmProperty);
                }

                var rowType = new RowType(listOfProperties);
                if (Schema.DataModel
                    == SchemaDataModelOption.EntityDataModel)
                {
                    rowType.DataSpace = DataSpace.CSpace;
                }
                else
                {
                    Debug.Assert(
                        Schema.DataModel == SchemaDataModelOption.ProviderDataModel,
                        "Only DataModel == SchemaDataModelOption.ProviderDataModel is expected");
                    rowType.DataSpace = DataSpace.SSpace;
                }

                rowType.AddMetadataProperties(OtherContent);
                _typeUsage = TypeUsage.Create(rowType);
            }
            return _typeUsage;
        }
        /// <summary>
        /// Initializes a new ModificationFunctionResultBinding instance.
        /// </summary>
        /// <param name="columnName">The name of the column to bind from the function result set.</param>
        /// <param name="property">The property to be set on the entity.</param>
        public ModificationFunctionResultBinding(string columnName, EdmProperty property)
        {
            Check.NotNull(columnName, "columnName");
            Check.NotNull(property, "property");

            _columnName = columnName;
            _property = property;
        }
        public ColumnMappingBuilder(EdmProperty columnProperty, IList<EdmProperty> propertyPath)
        {
            Check.NotNull(columnProperty, "columnProperty");
            Check.NotNull(propertyPath, "propertyPath");

            _columnProperty = columnProperty;
            _propertyPath = propertyPath;
        }
        internal StorageModificationFunctionResultBinding(string columnName, EdmProperty property)
        {
            DebugCheck.NotNull(columnName);
            DebugCheck.NotNull(property);

            ColumnName = columnName;
            Property = property;
        }
            public void Returns_rows_affected_when_there_is_a_reader()
            {
                var mockPrimitiveType = new Mock<PrimitiveType>();
                mockPrimitiveType.Setup(m => m.BuiltInTypeKind).Returns(BuiltInTypeKind.PrimitiveType);
                mockPrimitiveType.Setup(m => m.PrimitiveTypeKind).Returns(PrimitiveTypeKind.Int32);
                mockPrimitiveType.Setup(m => m.DataSpace).Returns(DataSpace.CSpace);
                string memberName = "property";
                var edmProperty = new EdmProperty(memberName, TypeUsage.Create(mockPrimitiveType.Object));

                var entityType = new EntityType("", "", DataSpace.CSpace, Enumerable.Empty<string>(), new[] { edmProperty });
                entityType.SetReadOnly();

                var mockUpdateTranslator = new Mock<UpdateTranslator>(MockBehavior.Strict);
                mockUpdateTranslator.Setup(m => m.CommandTimeout).Returns(() => null);
                var entityConnection = new Mock<EntityConnection>().Object;
                mockUpdateTranslator.Setup(m => m.Connection).Returns(entityConnection);

                var mockDbModificationCommandTree = new Mock<DbModificationCommandTree>();
                mockDbModificationCommandTree.SetupGet(m => m.HasReader).Returns(true);

                var mockDynamicUpdateCommand = new Mock<DynamicUpdateCommand>(new Mock<TableChangeProcessor>().Object, mockUpdateTranslator.Object,
                    ModificationOperator.Delete, PropagatorResult.CreateSimpleValue(PropagatorFlags.NoFlags, value: 0),
                    PropagatorResult.CreateStructuralValue(new[] { PropagatorResult.CreateSimpleValue(PropagatorFlags.NoFlags, value: 0) },
                        entityType,
                        isModified: false),
                    mockDbModificationCommandTree.Object, /*outputIdentifiers*/ null)
                {
                    CallBase = true
                };

                var mockDbCommand = new Mock<DbCommand>();

                int dbValue = 66;
                var mockDbDataReader = new Mock<DbDataReader>();
                mockDbDataReader.Setup(m => m.GetValue(It.IsAny<int>())).Returns(dbValue);
                int rowsToRead = 2;
                mockDbDataReader.Setup(m => m.Read()).Returns(() =>
                {
                    rowsToRead--;
                    return rowsToRead > 0;
                });
                mockDbDataReader.Setup(m => m.FieldCount).Returns(1);
                mockDbDataReader.Setup(m => m.GetName(0)).Returns(memberName);
                mockDbCommand.Protected().Setup<DbDataReader>("ExecuteDbDataReader", CommandBehavior.SequentialAccess).Returns(mockDbDataReader.Object);

                var identifierValues = new Dictionary<int, object>();

                mockDynamicUpdateCommand.Protected().Setup<DbCommand>("CreateCommand", identifierValues).Returns(mockDbCommand.Object);

                var generatedValues = new List<KeyValuePair<PropagatorResult, object>>();

                var rowsAffectedResult = mockDynamicUpdateCommand.Object.Execute(identifierValues, generatedValues);

                Assert.Equal(1, rowsAffectedResult);
                Assert.Equal(1, generatedValues.Count);
                Assert.Equal(dbValue, generatedValues[0].Value);
                Assert.Equal(0, generatedValues[0].Key.GetSimpleValue());
            }
        protected override void ConfigureProperty(EdmProperty property)
        {
            base.ConfigureProperty(property);

            if (IsUnicode != null)
            {
                property.IsUnicode = IsUnicode;
            }
        }
        internal override void Configure(EdmProperty property)
        {
            base.Configure(property);

            if (Precision != null)
            {
                property.Precision = Precision;
            }
        }
        internal override void Configure(EdmProperty property)
        {
            base.Configure(property);

            if (IsUnicode != null)
            {
                property.IsUnicode = IsUnicode;
            }
        }
 /// <summary>
 ///     Construct a new instance of the FieldDescriptor class that describes a property
 ///     on items of the supplied type.
 /// </summary>
 /// <param name="itemType"> Type of object whose property is described by this FieldDescriptor. </param>
 /// <param name="isReadOnly">
 ///     <b>True</b> if property value on item can be modified; otherwise <b>false</b> .
 /// </param>
 /// <param name="property"> EdmProperty that describes the property on the item. </param>
 internal FieldDescriptor(Type itemType, bool isReadOnly, EdmProperty property)
     : base(property.Name, null)
 {
     _itemType = itemType;
     _property = property;
     _isReadOnly = isReadOnly;
     _fieldType = DetermineClrType(_property.TypeUsage);
     Debug.Assert(_fieldType != null, "FieldDescriptor's CLR type has unexpected value of null.");
 }
        protected override void ConfigureProperty(EdmProperty property)
        {
            base.ConfigureProperty(property);

            if (Precision != null)
            {
                property.Precision = Precision;
            }
        }
 internal StateManagerMemberMetadata(ObjectPropertyMapping memberMap, EdmProperty memberMetadata, bool isPartOfKey)
 {
     DebugCheck.NotNull(memberMap);
     DebugCheck.NotNull(memberMetadata);
     _clrProperty = memberMap.ClrProperty;
     _edmProperty = memberMetadata;
     _isPartOfKey = isPartOfKey;
     _isComplexType = (Helper.IsEntityType(_edmProperty.TypeUsage.EdmType) ||
                       Helper.IsComplexType(_edmProperty.TypeUsage.EdmType));
 }
        public void Can_initialize_column_mapping_builder()
        {
            var columnProperty = new EdmProperty("C");
            var property = new EdmProperty("P");

            var columnMappingBuilder = new ColumnMappingBuilder(columnProperty, new[] { property });

            Assert.Same(columnProperty, columnMappingBuilder.ColumnProperty);
            Assert.Same(property, columnMappingBuilder.PropertyPath.Single());
        }
        public void Cannot_create_mapping_for_non_primitive_store_column()
        {
            var modelProperty = EdmProperty.Primitive("p", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32));
            var storeColumn = new EdmProperty("p", TypeUsage.CreateDefaultTypeUsage(new RowType()));

            Assert.Equal(
                Strings.StorageScalarPropertyMapping_OnlyScalarPropertiesAllowed,
                Assert.Throws<ArgumentException>(
                    () => new StorageScalarPropertyMapping(modelProperty, storeColumn)).Message);
        }
        public static void AddColumn(this EntityType table, EdmProperty column)
        {
            DebugCheck.NotNull(table);
            DebugCheck.NotNull(column);

            column.SetPreferredName(column.Name);
            column.Name = table.Properties.UniquifyName(column.Name);

            table.AddMember(column);
        }
Exemple #31
0
        internal void WritePropertyElementHeader(EdmProperty property)
        {
            DebugCheck.NotNull(property);

            _xmlWriter.WriteStartElement(XmlConstants.Property);
            _xmlWriter.WriteAttributeString(XmlConstants.Name, property.Name);
            _xmlWriter.WriteAttributeString(XmlConstants.TypeAttribute, GetTypeReferenceName(property));

            if (property.CollectionKind != CollectionKind.None)
            {
                _xmlWriter.WriteAttributeString(
                    XmlConstants.CollectionKind, property.CollectionKind.ToString());
            }

            if (property.ConcurrencyMode == ConcurrencyMode.Fixed)
            {
                _xmlWriter.WriteAttributeString(EdmProviderManifest.ConcurrencyModeFacetName, XmlConstants.Fixed);
            }

            WriteExtendedProperties(property);

            if (property.Annotations.GetClrAttributes() != null)
            {
                var epmCount = 0;
                foreach (var a in property.Annotations.GetClrAttributes())
                {
                    if (a.GetType().FullName.Equals(DataServicesMimeTypeAttribute, StringComparison.Ordinal))
                    {
                        var mimeType = a.GetType().GetDeclaredProperty("MimeType").GetValue(a, null) as string;
                        _xmlWriter.WriteAttributeString(DataServicesPrefix, "MimeType", DataServicesNamespace, mimeType);
                    }
                    else if (a.GetType().FullName.Equals(
                                 DataServicesEntityPropertyMappingAttribute, StringComparison.Ordinal))
                    {
                        var suffix = epmCount == 0
                                         ? String.Empty
                                         : string.Format(CultureInfo.InvariantCulture, "_{0}", epmCount);

                        var sourcePath = a.GetType().GetDeclaredProperty("SourcePath").GetValue(a, null) as string;
                        var slashIndex = sourcePath.IndexOf("/", StringComparison.Ordinal);
                        if (slashIndex != -1 &&
                            slashIndex + 1 < sourcePath.Length)
                        {
                            _xmlWriter.WriteAttributeString(
                                DataServicesPrefix, "FC_SourcePath" + suffix, DataServicesNamespace,
                                sourcePath.Substring(slashIndex + 1));
                        }

                        // There are three ways to write out this attribute
                        var    syndicationItem       = a.GetType().GetDeclaredProperty("TargetSyndicationItem").GetValue(a, null);
                        var    keepInContext         = a.GetType().GetDeclaredProperty("KeepInContent").GetValue(a, null).ToString();
                        var    criteriaValueProperty = a.GetType().GetDeclaredProperty("CriteriaValue");
                        string criteriaValue         = null;
                        if (criteriaValueProperty != null)
                        {
                            criteriaValue = criteriaValueProperty.GetValue(a, null) as string;
                        }

                        if (criteriaValue != null)
                        {
                            _xmlWriter.WriteAttributeString(
                                DataServicesPrefix,
                                "FC_TargetPath" + suffix,
                                DataServicesNamespace,
                                SyndicationItemPropertyToString(syndicationItem));
                            _xmlWriter.WriteAttributeString(
                                DataServicesPrefix, "FC_KeepInContent" + suffix, DataServicesNamespace,
                                keepInContext);
                            _xmlWriter.WriteAttributeString(
                                DataServicesPrefix, "FC_CriteriaValue" + suffix, DataServicesNamespace,
                                criteriaValue);
                        }
                        else if (string.Equals(
                                     syndicationItem.ToString(), "CustomProperty", StringComparison.Ordinal))
                        {
                            var targetPath            = a.GetType().GetDeclaredProperty("TargetPath").GetValue(a, null).ToString();
                            var targetNamespacePrefix =
                                a.GetType().GetDeclaredProperty("TargetNamespacePrefix").GetValue(a, null).ToString();
                            var targetNamespaceUri =
                                a.GetType().GetDeclaredProperty("TargetNamespaceUri").GetValue(a, null).ToString();

                            _xmlWriter.WriteAttributeString(
                                DataServicesPrefix, "FC_TargetPath" + suffix, DataServicesNamespace, targetPath);
                            _xmlWriter.WriteAttributeString(
                                DataServicesPrefix, "FC_NsUri" + suffix, DataServicesNamespace,
                                targetNamespaceUri);
                            _xmlWriter.WriteAttributeString(
                                DataServicesPrefix, "FC_NsPrefix" + suffix, DataServicesNamespace,
                                targetNamespacePrefix);
                            _xmlWriter.WriteAttributeString(
                                DataServicesPrefix, "FC_KeepInContent" + suffix, DataServicesNamespace,
                                keepInContext);
                        }
                        else
                        {
                            var contextKind = a.GetType().GetDeclaredProperty("TargetTextContentKind").GetValue(a, null);

                            _xmlWriter.WriteAttributeString(
                                DataServicesPrefix,
                                "FC_TargetPath" + suffix,
                                DataServicesNamespace,
                                SyndicationItemPropertyToString(syndicationItem));
                            _xmlWriter.WriteAttributeString(
                                DataServicesPrefix,
                                "FC_ContentKind" + suffix,
                                DataServicesNamespace,
                                SyndicationTextContentKindToString(contextKind));
                            _xmlWriter.WriteAttributeString(
                                DataServicesPrefix, "FC_KeepInContent" + suffix, DataServicesNamespace,
                                keepInContext);
                        }

                        epmCount++;
                    }
                }
            }

            if (property.IsMaxLength)
            {
                _xmlWriter.WriteAttributeString(XmlConstants.MaxLengthElement, XmlConstants.Max);
            }
            else if (!property.IsMaxLengthConstant &&
                     property.MaxLength.HasValue)
            {
                _xmlWriter.WriteAttributeString(
                    XmlConstants.MaxLengthElement,
                    property.MaxLength.Value.ToString(CultureInfo.InvariantCulture));
            }

            if (!property.IsFixedLengthConstant &&
                property.IsFixedLength.HasValue)
            {
                _xmlWriter.WriteAttributeString(
                    XmlConstants.FixedLengthElement,
                    GetLowerCaseStringFromBoolValue(property.IsFixedLength.Value));
            }

            if (!property.IsUnicodeConstant &&
                property.IsUnicode.HasValue)
            {
                _xmlWriter.WriteAttributeString(
                    XmlConstants.UnicodeElement, GetLowerCaseStringFromBoolValue(property.IsUnicode.Value));
            }

            if (!property.IsPrecisionConstant &&
                property.Precision.HasValue)
            {
                _xmlWriter.WriteAttributeString(
                    XmlConstants.PrecisionElement,
                    property.Precision.Value.ToString(CultureInfo.InvariantCulture));
            }

            if (!property.IsScaleConstant &&
                property.Scale.HasValue)
            {
                _xmlWriter.WriteAttributeString(
                    XmlConstants.ScaleElement, property.Scale.Value.ToString(CultureInfo.InvariantCulture));
            }

            if (property.StoreGeneratedPattern != StoreGeneratedPattern.None)
            {
                _xmlWriter.WriteAttributeString(
                    XmlConstants.StoreGeneratedPattern,
                    property.StoreGeneratedPattern == StoreGeneratedPattern.Computed
                        ? XmlConstants.Computed
                        : XmlConstants.Identity);
            }

            if (_serializeDefaultNullability || !property.Nullable)
            {
                _xmlWriter.WriteAttributeString(
                    EdmConstants.Nullable, GetLowerCaseStringFromBoolValue(property.Nullable));
            }

            MetadataProperty metadataProperty;

            if (property.MetadataProperties.TryGetValue(XmlConstants.StoreGeneratedPatternAnnotation, false, out metadataProperty))
            {
                _xmlWriter.WriteAttributeString(
                    XmlConstants.StoreGeneratedPattern, XmlConstants.AnnotationNamespace,
                    metadataProperty.Value.ToString());
            }
        }
Exemple #32
0
 // <summary>
 // Adds a property
 // </summary>
 // <param name="property"> The property to add </param>
 private void AddProperty(EdmProperty property)
 {
     Check.NotNull(property, "property");
     AddMember(property);
 }
Exemple #33
0
 // <summary>
 // Validate an EdmProperty object
 // </summary>
 // <param name="item"> The EdmProperty object to validate </param>
 // <param name="errors"> An error collection for adding validation errors </param>
 // <param name="validatedItems"> A dictionary keeping track of items that have been validated </param>
 private void ValidateEdmProperty(EdmProperty item, List <EdmItemError> errors, HashSet <MetadataItem> validatedItems)
 {
     ValidateEdmMember(item, errors, validatedItems);
 }
 /// <summary>
 ///     Create a column map for the entitysetid column
 /// </summary>
 private SimpleColumnMap CreateEntitySetIdColumnMap(md.EdmProperty prop)
 {
     return(CreateSimpleColumnMap(md.Helper.GetModelTypeUsage(prop), c_EntitySetIdColumnName));
 }
Exemple #35
0
        public void WriteEntityContainerMappingElement_should_write_function_import_elements()
        {
            var typeUsage =
                TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32));

            var complexTypeProperty1 = new EdmProperty("CTProperty1", typeUsage);
            var complexTypeProperty2 = new EdmProperty("CTProperty2", typeUsage);

            var complexType = new ComplexType("CT", "Ns", DataSpace.CSpace);

            complexType.AddMember(complexTypeProperty1);
            complexType.AddMember(complexTypeProperty2);

            var functionImport =
                new EdmFunction(
                    "f_c", "Ns", DataSpace.CSpace,
                    new EdmFunctionPayload
            {
                IsComposable     = true,
                IsFunctionImport = true,
                ReturnParameters =
                    new[]
                {
                    new FunctionParameter(
                        "ReturnValue",
                        TypeUsage.CreateDefaultTypeUsage(complexType.GetCollectionType()),
                        ParameterMode.ReturnValue)
                },
                Parameters =
                    new[]
                {
                    new FunctionParameter("param", typeUsage, ParameterMode.Out)
                }
            });

            typeUsage = ProviderRegistry.Sql2008_ProviderManifest.GetStoreType(typeUsage);
            var rowTypeProperty1 = new EdmProperty("RTProperty1", typeUsage);
            var rowTypeProperty2 = new EdmProperty("RTProperty2", typeUsage);
            var rowType          = new RowType(new[] { rowTypeProperty1, rowTypeProperty2 });

            var storeFunction =
                new EdmFunction(
                    "f_s", "Ns.Store", DataSpace.SSpace,
                    new EdmFunctionPayload
            {
                ReturnParameters =
                    new[]
                {
                    new FunctionParameter(
                        "Return",
                        TypeUsage.CreateDefaultTypeUsage(rowType),
                        ParameterMode.ReturnValue)
                },
                Parameters =
                    new[]
                {
                    new FunctionParameter("param", typeUsage, ParameterMode.Out)
                }
            });

            var structuralTypeMapping =
                new Tuple <StructuralType, List <ConditionPropertyMapping>, List <PropertyMapping> >(
                    complexType, new List <ConditionPropertyMapping>(), new List <PropertyMapping>());

            structuralTypeMapping.Item3.Add(new ScalarPropertyMapping(complexTypeProperty1, rowTypeProperty1));
            structuralTypeMapping.Item3.Add(new ScalarPropertyMapping(complexTypeProperty2, rowTypeProperty2));

            var functionImportMapping = new FunctionImportMappingComposable(
                functionImport,
                storeFunction,
                new List <Tuple <StructuralType, List <ConditionPropertyMapping>, List <PropertyMapping> > >
            {
                structuralTypeMapping
            });

            var containerMapping = new EntityContainerMapping(new EntityContainer("C", DataSpace.SSpace));

            containerMapping.AddFunctionImportMapping(functionImportMapping);

            var fixture = new Fixture();

            fixture.Writer.WriteEntityContainerMappingElement(containerMapping);

            Assert.Equal(
                @"<EntityContainerMapping StorageEntityContainer="""" CdmEntityContainer=""C"">
  <FunctionImportMapping FunctionName=""Ns.Store.f_s"" FunctionImportName=""f_c"">
    <ResultMapping>
      <ComplexTypeMapping TypeName=""Ns.CT"">
        <ScalarProperty Name=""CTProperty1"" ColumnName=""RTProperty1"" />
        <ScalarProperty Name=""CTProperty2"" ColumnName=""RTProperty2"" />
      </ComplexTypeMapping>
    </ResultMapping>
  </FunctionImportMapping>
</EntityContainerMapping>",
                fixture.ToString());
        }
Exemple #36
0
 /// <summary>
 ///     Try get the new property for the supplied propertyRef
 /// </summary>
 /// <param name="propertyRef"> property reference (on the old type) </param>
 /// <param name="throwIfMissing"> throw if the property is not found </param>
 /// <param name="newProperty"> the corresponding property on the new type </param>
 internal bool TryGetNewProperty(PropertyRef propertyRef, bool throwIfMissing, out md.EdmProperty newProperty)
 {
     return(RootType.TryGetNewProperty(propertyRef, throwIfMissing, out newProperty));
 }
 private void AddProperty(EdmProperty property)
 {
     Check.NotNull <EdmProperty>(property, nameof(property));
     this.AddMember((EdmMember)property);
 }
Exemple #38
0
 protected internal override void VisitEdmProperty(EdmProperty item)
 {
     _schemaWriter.WritePropertyElementHeader(item);
     base.VisitEdmProperty(item);
     _schemaWriter.WriteEndElement();
 }