public void HasColumnOrder_should_throw_when_argument_out_of_range()
        {
            var configuration = new PrimitivePropertyConfiguration<PrimitivePropertyConfiguration>(new PrimitivePropertyConfiguration());

            Assert.Equal(
                new ArgumentOutOfRangeException("columnOrder").Message,
                Assert.Throws<ArgumentOutOfRangeException>(() => configuration.HasColumnOrder(-1)).Message);
        }
        public void Apply_should_ignore_attribute_if_already_set()
        {
            var propertyConfiguration = new PrimitivePropertyConfiguration { DatabaseGeneratedOption = DatabaseGeneratedOption.Computed };

            new DatabaseGeneratedAttributeConvention.DatabaseGeneratedAttributeConventionImpl()
                .Apply(new MockPropertyInfo(), propertyConfiguration, new DatabaseGeneratedAttribute(DatabaseGeneratedOption.None));

            Assert.Equal(DatabaseGeneratedOption.Computed, propertyConfiguration.DatabaseGeneratedOption);
        }
        public void Apply_should_set_store_generated_pattern()
        {
            var propertyConfiguration = new PrimitivePropertyConfiguration();

            new DatabaseGeneratedAttributeConvention()
                .Apply(new MockPropertyInfo(), propertyConfiguration, new DatabaseGeneratedAttribute(DatabaseGeneratedOption.None));

            Assert.Equal(DatabaseGeneratedOption.None, propertyConfiguration.DatabaseGeneratedOption);
        }
 internal override void CopyFrom(PrimitivePropertyConfiguration other)
 {
     base.CopyFrom(other);
     var strConfigRhs = other as DateTimePropertyConfiguration;
     if (strConfigRhs != null)
     {
         Precision = strConfigRhs.Precision;
     }
 }
 internal override void CopyFrom(PrimitivePropertyConfiguration other)
 {
     base.CopyFrom(other);
     var strConfigRhs = other as StringPropertyConfiguration;
     if (strConfigRhs != null)
     {
         IsUnicode = strConfigRhs.IsUnicode;
     }
 }
        public void HasDatabaseGeneratedOption_should_throw_when_argument_out_of_range()
        {
            var configuration = new PrimitivePropertyConfiguration<PrimitivePropertyConfiguration>(new PrimitivePropertyConfiguration());

            Assert.Equal(
                new ArgumentOutOfRangeException("databaseGeneratedOption").Message,
                Assert.Throws<ArgumentOutOfRangeException>(() => configuration.HasDatabaseGeneratedOption((DatabaseGeneratedOption?)(-1))).
                    Message);
        }
 internal override void CopyFrom(PrimitivePropertyConfiguration other)
 {
     base.CopyFrom(other);
     var strConfigRhs = other as BinaryPropertyConfiguration;
     if (strConfigRhs != null)
     {
         IsRowVersion = strConfigRhs.IsRowVersion;
     }
 }
        public void Apply_should_not_set_column_name_when_already_set()
        {
            var propertyConfiguration = new PrimitivePropertyConfiguration { ColumnName = "Bar" };

            new ColumnAttributeConvention.ColumnAttributeConventionImpl()
                .Apply(new MockPropertyInfo(), propertyConfiguration, new ColumnAttribute("Foo"));

            Assert.Equal("Bar", propertyConfiguration.ColumnName);
        }
        public void Apply_should_set_concurrency_token()
        {
            var propertyConfiguration = new PrimitivePropertyConfiguration();

            new ConcurrencyCheckAttributeConvention.ConcurrencyCheckAttributeConventionImpl()
                .Apply(new MockPropertyInfo(), propertyConfiguration, new ConcurrencyCheckAttribute());

            Assert.Equal(EdmConcurrencyMode.Fixed, propertyConfiguration.ConcurrencyMode);
        }
        public void Apply_should_set_column_name()
        {
            var propertyConfiguration = new PrimitivePropertyConfiguration();

            new ColumnAttributeConvention.ColumnAttributeConventionImpl()
                .Apply(new MockPropertyInfo(), propertyConfiguration, new ColumnAttribute("Foo"));

            Assert.Equal("Foo", propertyConfiguration.ColumnName);
        }
        public void Apply_should_ignore_attribute_if_already_set()
        {
            var propertyConfiguration = new PrimitivePropertyConfiguration { ConcurrencyMode = EdmConcurrencyMode.None };

            new ConcurrencyCheckAttributeConvention.ConcurrencyCheckAttributeConventionImpl()
                .Apply(new MockPropertyInfo(), propertyConfiguration, new ConcurrencyCheckAttribute());

            Assert.Equal(EdmConcurrencyMode.None, propertyConfiguration.ConcurrencyMode);
        }
 public override void FillFrom(PrimitivePropertyConfiguration other, bool inCSpace)
 {
     base.FillFrom(other, inCSpace);
     var strConfigRhs = other as BinaryPropertyConfiguration;
     if (strConfigRhs != null
         && IsRowVersion == null)
     {
         IsRowVersion = strConfigRhs.IsRowVersion;
     }
 }
        public void HasParameterName_configures_when_unset()
        {
            var innerConfig = new PrimitivePropertyConfiguration();
            var config = new LightweightPropertyConfiguration(new MockPropertyInfo(), () => innerConfig);

            var result = config.HasParameterName("Parameter1");

            Assert.Equal("Parameter1", innerConfig.ParameterName);
            Assert.Same(config, result);
        }
 internal override void CopyFrom(PrimitivePropertyConfiguration other)
 {
     base.CopyFrom(other);
     var lenConfigRhs = other as DecimalPropertyConfiguration;
     if (lenConfigRhs != null)
     {
         Precision = lenConfigRhs.Precision;
         Scale = lenConfigRhs.Scale;
     }
 }
        internal override bool IsCompatible(PrimitivePropertyConfiguration other, bool inCSpace, out string errorMessage)
        {
            var dateRhs = other as DateTimePropertyConfiguration;

            var baseIsCompatible = base.IsCompatible(other, inCSpace, out errorMessage);
            var precisionIsCompatible = dateRhs == null || IsCompatible(c => c.Precision, dateRhs, ref errorMessage);

            return baseIsCompatible &&
                   precisionIsCompatible;
        }
 internal override void FillFrom(PrimitivePropertyConfiguration other, bool inCSpace)
 {
     base.FillFrom(other, inCSpace);
     var strConfigRhs = other as DateTimePropertyConfiguration;
     if (strConfigRhs != null
         && Precision == null)
     {
         Precision = strConfigRhs.Precision;
     }
 }
        internal override bool IsCompatible(PrimitivePropertyConfiguration other, bool inCSpace, out string errorMessage)
        {
            var stringRhs = other as StringPropertyConfiguration;

            var baseIsCompatible = base.IsCompatible(other, inCSpace, out errorMessage);
            var isUnicodeIsCompatible = stringRhs == null || IsCompatible(c => c.IsUnicode, stringRhs, ref errorMessage);

            return baseIsCompatible &&
                   isUnicodeIsCompatible;
        }
 internal override void FillFrom(PrimitivePropertyConfiguration other, bool inCSpace)
 {
     base.FillFrom(other, inCSpace);
     var strConfigRhs = other as StringPropertyConfiguration;
     if (strConfigRhs != null
         && IsUnicode == null)
     {
         IsUnicode = strConfigRhs.IsUnicode;
     }
 }
        public void HasParameterName_should_set_name_on_inner_configuration()
        {
            var innerConfiguration = CreateConfiguration();
            var primitivePropertyConfiguration 
                = new PrimitivePropertyConfiguration<PrimitivePropertyConfiguration>(innerConfiguration);

            primitivePropertyConfiguration.HasParameterName("Foo");

            Assert.Equal("Foo", innerConfiguration.ParameterName);
        }
        internal override void MakeCompatibleWith(PrimitivePropertyConfiguration other, bool inCSpace)
        {
            DebugCheck.NotNull(other);

            base.MakeCompatibleWith(other, inCSpace);

            var stringPropertyConfiguration = other as StringPropertyConfiguration;

            if (stringPropertyConfiguration == null) return;
            if (stringPropertyConfiguration.IsUnicode != null) IsUnicode = null;
        }
 internal override void CopyFrom(PrimitivePropertyConfiguration other)
 {
     base.CopyFrom(other);
     var lenConfigRhs = other as LengthPropertyConfiguration;
     if (lenConfigRhs != null)
     {
         IsFixedLength = lenConfigRhs.IsFixedLength;
         MaxLength = lenConfigRhs.MaxLength;
         IsMaxLength = lenConfigRhs.IsMaxLength;
     }
 }
        internal override void MakeCompatibleWith(PrimitivePropertyConfiguration other, bool inCSpace)
        {
            DebugCheck.NotNull(other);

            base.MakeCompatibleWith(other, inCSpace);

            var dateTimePropertyConfiguration = other as DateTimePropertyConfiguration;

            if (dateTimePropertyConfiguration == null) return;
            if (dateTimePropertyConfiguration.Precision != null) Precision = null;
        }
Exemplo n.º 23
0
        public void Apply_invokes_action_when_no_predicates()
        {
            var actionInvoked = false;
            var convention = new PropertyConvention(
                Enumerable.Empty<Func<PropertyInfo, bool>>(),
                c => actionInvoked = true);
            var propertyInfo = new MockPropertyInfo();
            var configuration = new PrimitivePropertyConfiguration();

            convention.Apply(propertyInfo, () => configuration);

            Assert.True(actionInvoked);
        }
Exemplo n.º 24
0
        public void Apply_does_not_invoke_action_when_single_predicate_false()
        {
            var actionInvoked = false;
            var convention = new PropertyConvention(
                new Func<PropertyInfo, bool>[] { p => false },
                c => actionInvoked = true);
            var propertyInfo = new MockPropertyInfo();
            var configuration = new PrimitivePropertyConfiguration();

            convention.Apply(propertyInfo, () => configuration);

            Assert.False(actionInvoked);
        }
        public static void ColumnName_is_set_on_internal_configuration()
        {
            var primitivePropertyConfiguration = new PrimitivePropertyConfiguration();
            primitivePropertyConfiguration.ColumnName = "A";

            Assert.Equal("A", primitivePropertyConfiguration.ColumnName);

            var propertyMappingConfiguration = 
                new PropertyMappingConfiguration(primitivePropertyConfiguration);
            propertyMappingConfiguration.HasColumnName("B");

            Assert.Equal("B", primitivePropertyConfiguration.ColumnName);
        }
        public void HasColumnName_is_noop_when_set()
        {
            var innerConfig = new PrimitivePropertyConfiguration
                                  {
                                      ColumnName = "Column1"
                                  };
            var config = new LightweightPropertyConfiguration(new MockPropertyInfo(), () => innerConfig);

            var result = config.HasColumnName("Column2");

            Assert.Equal("Column1", innerConfig.ColumnName);
            Assert.Same(config, result);
        }
        public void Apply_does_not_invoke_action_when_value_null()
        {
            var actionInvoked = false;
            var convention = new PropertyConventionWithHaving<object>(
                Enumerable.Empty<Func<PropertyInfo, bool>>(),
                p => null,
                (c, v) => actionInvoked = true);
            var propertyInfo = new MockPropertyInfo();
            var configuration = new PrimitivePropertyConfiguration();

            convention.Apply(propertyInfo, () => configuration);

            Assert.False(actionInvoked);
        }
        public void TimestampConvention_AppliesWhenTheAttributeIsAppliedToASingleProperty()
        {
            // Arrange
            PropertyInfo property = CreateMockPropertyInfo("TestProperty");
            EntityTypeConfiguration entityType = new EntityTypeConfiguration();
            PrimitivePropertyConfiguration primitiveProperty = new PrimitivePropertyConfiguration(property, entityType);
            entityType.ExplicitProperties.Add(property, primitiveProperty);
            TimestampAttributeEdmPropertyConvention convention = new TimestampAttributeEdmPropertyConvention();

            // Act
            convention.Apply(primitiveProperty, entityType);

            // Assert
            Assert.True(primitiveProperty.ConcurrencyToken);
        }
        public void TimestampConvention_DoesntApplyWhenTheAttributeIsAppliedOnANonEntityType()
        {
            // Arrange
            PropertyInfo property = CreateMockPropertyInfo("TestProperty");
            ComplexTypeConfiguration complexType = new ComplexTypeConfiguration();
            PrimitivePropertyConfiguration primitiveProperty = new PrimitivePropertyConfiguration(property, complexType);
            complexType.ExplicitProperties.Add(property, primitiveProperty);
            TimestampAttributeEdmPropertyConvention convention = new TimestampAttributeEdmPropertyConvention();

            // Act
            convention.Apply(primitiveProperty, complexType);

            // Assert
            Assert.False(primitiveProperty.ConcurrencyToken);
        }
        public void AsTimeOfDay_Works()
        {
            // Arrange
            MockType     type     = new MockType().Property(typeof(TimeSpan), "CreatedTime");
            PropertyInfo property = type.GetProperty("CreatedTime");

            _structuralType.Setup(t => t.ClrType).Returns(type);

            // Act
            PrimitivePropertyConfiguration propertyConfig = new PrimitivePropertyConfiguration(property, _structuralType.Object);
            EdmPrimitiveTypeKind?          typeKind       = propertyConfig.AsTimeOfDay().TargetEdmTypeKind;

            // Assert
            Assert.NotNull(typeKind);
            Assert.Equal(EdmPrimitiveTypeKind.TimeOfDay, typeKind);
        }
        private static IndexAnnotation GetIndexAnnotation(PrimitivePropertyConfiguration propertyConfiguration)
        {
            var configuration = typeof (PrimitivePropertyConfiguration)
                .GetProperty("Configuration", BindingFlags.Instance | BindingFlags.NonPublic)
                .GetValue(propertyConfiguration, null);

            var annotations = (IDictionary<string, object>) configuration.GetType()
                .GetProperty("Annotations", BindingFlags.Instance | BindingFlags.Public)
                .GetValue(configuration, null);

            object annotation;
            if (!annotations.TryGetValue(IndexAnnotation.AnnotationName, out annotation))
                return null;

            return annotation as IndexAnnotation;
        }
        public void AsDate_Works()
        {
            // Arrange
            MockType     type     = new MockType().Property(typeof(DateTime), "Birthday");
            PropertyInfo property = type.GetProperty("Birthday");

            _structuralType.Setup(t => t.ClrType).Returns(type);

            // Act
            PrimitivePropertyConfiguration propertyConfig = new PrimitivePropertyConfiguration(property, _structuralType.Object);
            EdmPrimitiveTypeKind?          typeKind       = propertyConfig.AsDate().TargetEdmTypeKind;

            // Assert
            Assert.NotNull(typeKind);
            Assert.Equal(EdmPrimitiveTypeKind.Date, typeKind);
        }
Exemplo n.º 33
0
        public void TimestampConvention_AppliesWhenTheAttributeIsAppliedToASingleProperty()
        {
            // Arrange
            PropertyInfo                   property          = CreateMockPropertyInfo("TestProperty");
            EntityTypeConfiguration        entityType        = new EntityTypeConfiguration();
            PrimitivePropertyConfiguration primitiveProperty = new PrimitivePropertyConfiguration(property, entityType);

            entityType.ExplicitProperties.Add(property, primitiveProperty);
            TimestampAttributeEdmPropertyConvention convention = new TimestampAttributeEdmPropertyConvention();

            // Act
            convention.Apply(primitiveProperty, entityType, ODataConventionModelBuilderFactory.Create());

            // Assert
            Assert.True(primitiveProperty.ConcurrencyToken);
        }
Exemplo n.º 34
0
        public void RemoveKey_Removes_KeyProperty()
        {
            // Arrange
            var builder    = new ODataModelBuilder();
            var motorcycle = builder.AddEntityType(typeof(Motorcycle));
            PrimitivePropertyConfiguration modelProperty = motorcycle.AddProperty(typeof(Motorcycle).GetProperty("Model"));

            motorcycle.HasKey(typeof(Motorcycle).GetProperty("Model"));
            Assert.Equal(new[] { modelProperty }, motorcycle.Keys);

            // Act
            motorcycle.RemoveKey(modelProperty);

            // Assert
            Assert.Empty(motorcycle.Keys);
        }
Exemplo n.º 35
0
        public void Property_IsNotNavigable_SetsNotSortableAndNotFilterable()
        {
            // Arrange
            StructuralTypeConfiguration structuralType = Mock.Of <StructuralTypeConfiguration>();
            Mock <PropertyInfo>         propertyInfo   = new Mock <PropertyInfo>();

            propertyInfo.SetupGet(p => p.PropertyType).Returns(typeof(int));
            PropertyConfiguration property = new PrimitivePropertyConfiguration(propertyInfo.Object, structuralType);

            // Act
            property.IsNotNavigable();

            // Assert
            Assert.True(property.NotFilterable);
            Assert.True(property.NotSortable);
        }
Exemplo n.º 36
0
        public void TimestampConvention_DoesntApplyWhenTheAttributeIsAppliedOnANonEntityType()
        {
            // Arrange
            PropertyInfo                   property          = CreateMockPropertyInfo("TestProperty");
            ComplexTypeConfiguration       complexType       = new ComplexTypeConfiguration();
            PrimitivePropertyConfiguration primitiveProperty = new PrimitivePropertyConfiguration(property, complexType);

            complexType.ExplicitProperties.Add(property, primitiveProperty);
            TimestampAttributeEdmPropertyConvention convention = new TimestampAttributeEdmPropertyConvention();

            // Act
            convention.Apply(primitiveProperty, complexType, ODataConventionModelBuilderFactory.Create());

            // Assert
            Assert.False(primitiveProperty.ConcurrencyToken);
        }
 public override void FillFrom(PrimitivePropertyConfiguration other, bool inCSpace)
 {
     base.FillFrom(other, inCSpace);
     var lenConfigRhs = other as DecimalPropertyConfiguration;
     if (lenConfigRhs != null)
     {
         if (Precision == null)
         {
             Precision = lenConfigRhs.Precision;
         }
         if (Scale == null)
         {
             Scale = lenConfigRhs.Scale;
         }
     }
 }
        private static void ApplyNavigation(NavigationPropertyConfiguration navProperty, EntityTypeConfiguration entityType,
                                            ForeignKeyAttribute foreignKeyAttribute)
        {
            Contract.Assert(navProperty != null);
            Contract.Assert(entityType != null);
            Contract.Assert(foreignKeyAttribute != null);

            if (navProperty.AddedExplicitly || navProperty.Multiplicity == EdmMultiplicity.Many)
            {
                return;
            }

            EntityTypeConfiguration principalEntity = entityType.ModelBuilder.StructuralTypes
                                                      .OfType <EntityTypeConfiguration>().FirstOrDefault(e => e.ClrType == navProperty.RelatedClrType);

            if (principalEntity == null)
            {
                return;
            }

            // if a navigation property has multiple foreign keys, use comma to separate the list of foreign key names.
            IEnumerable <string> dependentPropertyNames = foreignKeyAttribute.Name.Split(',').Select(p => p.Trim());

            foreach (string dependentPropertyName in dependentPropertyNames)
            {
                if (String.IsNullOrWhiteSpace(dependentPropertyName))
                {
                    continue;
                }

                PrimitivePropertyConfiguration dependent =
                    entityType.Properties.OfType <PrimitivePropertyConfiguration>()
                    .SingleOrDefault(p => p.Name.Equals(dependentPropertyName, StringComparison.Ordinal));

                if (dependent != null)
                {
                    Type dependentType = Nullable.GetUnderlyingType(dependent.PropertyInfo.PropertyType) ?? dependent.PropertyInfo.PropertyType;
                    PrimitivePropertyConfiguration principal = principalEntity.Keys.FirstOrDefault(
                        k => k.PropertyInfo.PropertyType == dependentType && navProperty.PrincipalProperties.All(p => p != k.PropertyInfo));

                    if (principal != null)
                    {
                        navProperty.HasConstraint(dependent.PropertyInfo, principal.PropertyInfo);
                    }
                }
            }
        }
Exemplo n.º 39
0
        public void Apply_does_not_invoke_action_when_last_predicate_false()
        {
            var actionInvoked = false;
            var convention    = new PropertyConvention(
                new Func <PropertyInfo, bool>[]
            {
                p => true,
                p => false
            },
                c => actionInvoked = true);
            var propertyInfo  = new MockPropertyInfo();
            var configuration = new PrimitivePropertyConfiguration();

            convention.Apply(propertyInfo, () => configuration);

            Assert.False(actionInvoked);
        }
        public static PrimitivePropertyConfiguration PrivateProperty <T, U>(
            this EntityTypeConfiguration <T> mapper,
            Expression <Func <T, U?> > exp,
            NamingConventions?convention = null)
            where T : class
            where U : struct
        {
            mapper.Ignore(exp);
            dynamic expression = exp;
            string  defaultColumnName;

            ExpressionModifier.ToPrivate(ref expression, convention, out defaultColumnName);
            PrimitivePropertyConfiguration configuration = mapper.Property(expression);

            configuration.HasColumnName(defaultColumnName);
            return(configuration);
        }
        public void TimestampConvention_DoesntApplyWhenTheAttributeIsAppliedToMultipleProperties()
        {
            // Arrange
            PropertyInfo                   property          = CreateMockPropertyInfo("TestProperty");
            PropertyInfo                   otherProperty     = CreateMockPropertyInfo("OtherTestProperty");
            EntityTypeConfiguration        entityType        = new EntityTypeConfiguration();
            PrimitivePropertyConfiguration primitiveProperty = new PrimitivePropertyConfiguration(property, entityType);

            entityType.ExplicitProperties.Add(property, primitiveProperty);
            entityType.ExplicitProperties.Add(otherProperty, new PrimitivePropertyConfiguration(otherProperty, entityType));
            TimestampAttributeEdmPropertyConvention convention = new TimestampAttributeEdmPropertyConvention();

            // Act
            convention.Apply(primitiveProperty, entityType, new ODataConventionModelBuilder());

            // Assert
            Assert.False(primitiveProperty.ConcurrencyToken);
        }
Exemplo n.º 42
0
        public void Convert(Metadata data, PrimitivePropertyConfiguration configuration)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            Configuration = configuration;
            ConvertToConfiguration(data);
            if (adapter != null)
            {
                adapter.Convert(data, configuration);
            }
        }
        /// <summary>
        /// Marks the property with concurrency token on the EDM type.
        /// </summary>
        /// <param name="edmProperty">The EDM property.</param>
        /// <param name="structuralTypeConfiguration">The EDM type being configured.</param>
        /// <param name="attribute">The <see cref="Attribute"/> found.</param>
        /// <param name="model">The ODataConventionModelBuilder used to build the model.</param>
        public override void Apply(PropertyConfiguration edmProperty,
                                   StructuralTypeConfiguration structuralTypeConfiguration,
                                   Attribute attribute,
                                   ODataConventionModelBuilder model)
        {
            if (edmProperty == null)
            {
                throw Error.ArgumentNull("edmProperty");
            }

            EntityTypeConfiguration        entityType        = structuralTypeConfiguration as EntityTypeConfiguration;
            PrimitivePropertyConfiguration primitiveProperty = edmProperty as PrimitivePropertyConfiguration;

            if (entityType != null && primitiveProperty != null)
            {
                primitiveProperty.ConcurrencyToken = true;
            }
        }
Exemplo n.º 44
0
        public void CanAddPrimitiveProperty_ForTargetEntityType()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            // Act
            builder.EntityType <ForeignEntity>().HasRequired(c => c.Principal, (c, r) => c.ForeignKey1 == r.PrincipalKey1);

            // Assert
            EntityTypeConfiguration principalEntityType = Assert.Single(
                builder.StructuralTypes.OfType <EntityTypeConfiguration>().Where(e => e.Name == "ForeignPrincipal"));

            PropertyConfiguration          propertyConfig  = Assert.Single(principalEntityType.Properties);
            PrimitivePropertyConfiguration primitiveConfig =
                Assert.IsType <PrimitivePropertyConfiguration>(propertyConfig);

            Assert.Equal("PrincipalKey1", primitiveConfig.Name);
            Assert.Equal("System.Int32", primitiveConfig.RelatedClrType.FullName);
        }
Exemplo n.º 45
0
        /// <summary>
        ///     Applies an index to <paramref name="property" />.
        /// </summary>
        /// <remarks>
        ///     Note: If the indexed property is of type string, you have to set the MaxLength.
        /// </remarks>
        /// <param name="property">The property instance.</param>
        /// <param name="indexName">The name of the database index. Default is "IX_Default" if not defined.</param>
        /// <param name="isUnique">
        ///     Set this property to true to define a unique index. Set this property to false to define a
        ///     non-unique index.
        /// </param>
        /// <param name="columnOrder">The column order of the index. Default is 0 if not defined.</param>
        /// <returns></returns>
        public static PrimitivePropertyConfiguration HasIndex(
            this PrimitivePropertyConfiguration property,
            string indexName = "",
            bool isUnique    = false,
            int columnOrder  = 0)
        {
            if (string.IsNullOrEmpty(indexName))
            {
                indexName = $"{IndexConstants.IndexPrefix}_{IndexConstants.DefaultIndexName}";
            }

            var indexAttribute = new IndexAttribute(indexName, columnOrder)
            {
                IsUnique = isUnique
            };
            var indexAnnotation = new IndexAnnotation(indexAttribute);

            return(property.HasColumnAnnotation(IndexAnnotation.AnnotationName, indexAnnotation));
        }
        private static void CreateIndex(
            PrimitivePropertyConfiguration property,
            bool isUnique = false,
            string name   = null,
            int position  = 1)
        {
            var indexAttribute = new IndexAttribute();

            if (!string.IsNullOrWhiteSpace(name))
            {
                indexAttribute = new IndexAttribute(
                    name,
                    position <= 0 ? 1 : position);
            }
            indexAttribute.IsUnique = isUnique;
            property.HasColumnAnnotation(
                IndexAnnotation.AnnotationName,
                new IndexAnnotation(indexAttribute));
        }
Exemplo n.º 47
0
        /// <summary>
        /// Marks the property with StoreGeneratedPattern on the EDM type.
        /// </summary>
        /// <param name="edmProperty">The EDM property.</param>
        /// <param name="structuralTypeConfiguration">The EDM type being configured.</param>
        /// <param name="attribute">The <see cref="Attribute"/> found.</param>
        public override void Apply(PropertyConfiguration edmProperty,
                                   StructuralTypeConfiguration structuralTypeConfiguration, Attribute attribute)
        {
            if (edmProperty == null)
            {
                throw Error.ArgumentNull("edmProperty");
            }

            EntityTypeConfiguration        entityType                 = structuralTypeConfiguration as EntityTypeConfiguration;
            PrimitivePropertyConfiguration primitiveProperty          = edmProperty as PrimitivePropertyConfiguration;
            DatabaseGeneratedAttribute     databaseGeneratedAttribute = attribute as DatabaseGeneratedAttribute;

            if (entityType != null && primitiveProperty != null && databaseGeneratedAttribute != null)
            {
                if (!edmProperty.AddedExplicitly)
                {
                    primitiveProperty.StoreGeneratedPattern = databaseGeneratedAttribute.DatabaseGeneratedOption;
                }
            }
        }
Exemplo n.º 48
0
        public void CanAddPrimitiveProperty_ForDependentEntityType()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            // Act
            builder.EntityType <ForeignEntity>().HasRequired(c => c.Principal, (c, r) => c.ForeignKey1 == r.PrincipalKey1);

            // Assert
            EntityTypeConfiguration dependentEntityType =
                builder.StructuralTypes.OfType <EntityTypeConfiguration>().FirstOrDefault(e => e.Name == "ForeignEntity");

            Assert.NotNull(dependentEntityType);

            PrimitivePropertyConfiguration primitiveConfig =
                Assert.Single(dependentEntityType.Properties.OfType <PrimitivePropertyConfiguration>());

            Assert.Equal("ForeignKey1", primitiveConfig.Name);
            Assert.Equal("System.Int32", primitiveConfig.RelatedClrType.FullName);
        }
Exemplo n.º 49
0
        public void CreateDatePrimitiveProperty()
        {
            // Arrange
            ODataModelBuilder builder           = new ODataModelBuilder();
            EntityTypeConfiguration <File> file = builder.EntityType <File>();
            PrimitivePropertyConfiguration date = file.Property(f => f.DateProperty);

            // Act
            IEdmModel model = builder.GetServiceModel();

            // Assert
            Assert.Equal(PropertyKind.Primitive, date.Kind);

            IEdmEntityType fileType = Assert.Single(model.SchemaElements.OfType <IEdmEntityType>());

            IEdmProperty dateProperty = Assert.Single(fileType.DeclaredProperties.Where(p => p.Name == "DateProperty"));

            Assert.NotNull(dateProperty);
            Assert.Equal("Edm.Date", dateProperty.Type.FullName());
        }
        public void Apply_invokes_action_with_value_when_not_null()
        {
            var    actionInvoked = false;
            object capturedValue = null;
            var    value         = new object();
            var    convention    = new PropertyConventionWithHaving <object>(
                Enumerable.Empty <Func <PropertyInfo, bool> >(),
                p => value,
                (c, v) =>
            {
                actionInvoked = true;
                capturedValue = v;
            });
            var propertyInfo  = new MockPropertyInfo();
            var configuration = new PrimitivePropertyConfiguration();

            convention.Apply(propertyInfo, () => configuration);

            Assert.True(actionInvoked);
            Assert.Same(value, capturedValue);
        }
        private static void ApplyPrimitive(PrimitivePropertyConfiguration dependent, EntityTypeConfiguration entityType,
                                           ForeignKeyAttribute foreignKeyAttribute)
        {
            Contract.Assert(dependent != null);
            Contract.Assert(entityType != null);
            Contract.Assert(foreignKeyAttribute != null);

            string navName = foreignKeyAttribute.Name.Trim();
            NavigationPropertyConfiguration navProperty = entityType.NavigationProperties
                                                          .FirstOrDefault(n => n.Name.Equals(navName, StringComparison.Ordinal));

            if (navProperty == null)
            {
                return;
            }

            if (navProperty.Multiplicity == EdmMultiplicity.Many || navProperty.AddedExplicitly)
            {
                return;
            }

            EntityTypeConfiguration principalEntity = entityType.ModelBuilder.StructuralTypes
                                                      .OfType <EntityTypeConfiguration>().FirstOrDefault(e => e.ClrType == navProperty.RelatedClrType);

            if (principalEntity == null)
            {
                return;
            }

            PrimitivePropertyConfiguration principal =
                principalEntity.Keys.FirstOrDefault(
                    k => k.PropertyInfo.PropertyType == dependent.PropertyInfo.PropertyType &&
                    navProperty.PrincipalProperties.All(p => p != k.PropertyInfo));

            if (principal != null)
            {
                navProperty.HasConstraint(dependent.PropertyInfo, principal.PropertyInfo);
            }
        }
        public void Keys_Returns_DerivedKeys_IfBaseTypePresent()
        {
            // Arrange
            PrimitivePropertyConfiguration[] keys = new PrimitivePropertyConfiguration[0];


            Mock <EntityTypeConfiguration> baseBaseEntity = new Mock <EntityTypeConfiguration>();

            baseBaseEntity.Setup(e => e.Keys).Returns(keys);
            baseBaseEntity.Setup(e => e.BaseType).Returns <EntityTypeConfiguration>(null);

            Mock <EntityTypeConfiguration> baseEntity = new Mock <EntityTypeConfiguration>();

            baseEntity.Setup(e => e.BaseType).Returns(baseBaseEntity.Object);

            Mock <EntityTypeConfiguration> entity = new Mock <EntityTypeConfiguration>();

            baseEntity.Setup(e => e.BaseType).Returns(baseEntity.Object);

            // Act & Assert
            Assert.Equal(keys, entity.Object.Keys());
        }
        public static PrimitivePropertyConfiguration HasIdentityConfiguration(
            this PrimitivePropertyConfiguration @this,
            int seedValue = 1)
        {
            //@this.HasDatabaseGeneratedOption(
            //		DatabaseGeneratedOption.Identity)
            //		.HasColumnAnnotation("");

            //var configuration = @this
            //	.HasDatabaseGeneratedOption(
            //		DatabaseGeneratedOption.Identity)
            //		.Reflect()
            //		.GetPropertyValue<object>(
            //			ReflectionVisibility.InstanceNonPublic, "Configuration");

            //var annotations = configuration
            //	.Reflect()
            //	.GetPropertyValue<IDictionary<string, object>>(
            //		ReflectionVisibility.InstanceNonPublic, "Annotations");


            return(@this);
        }
Exemplo n.º 54
0
        private PrimitivePropertyConfiguration Cloning_a_primitive_property_configuration_clones_its_property_information_implementation(
            PrimitivePropertyConfiguration configuration)
        {
            configuration.IsNullable                    = true;
            configuration.ConcurrencyMode               = ConcurrencyMode.Fixed;
            configuration.DatabaseGeneratedOption       = DatabaseGeneratedOption.Identity;
            configuration.ColumnType                    = "ColumnType";
            configuration.ColumnName                    = "ColumnName";
            configuration.ColumnOrder                   = 1;
            configuration.OverridableConfigurationParts = OverridableConfigurationParts.OverridableInCSpace;

            var clone = configuration.Clone();

            Assert.True(clone.IsNullable.Value);
            Assert.Equal(ConcurrencyMode.Fixed, clone.ConcurrencyMode);
            Assert.Equal(DatabaseGeneratedOption.Identity, clone.DatabaseGeneratedOption);
            Assert.Equal("ColumnType", clone.ColumnType);
            Assert.Equal("ColumnName", clone.ColumnName);
            Assert.Equal(1, clone.ColumnOrder);
            Assert.Equal(OverridableConfigurationParts.OverridableInCSpace, clone.OverridableConfigurationParts);

            return(clone);
        }
        public void Configure_should_preserve_the_most_derived_configuration()
        {
            var configurationA = CreateConfiguration();

            configurationA.ConcurrencyMode = ConcurrencyMode.Fixed;
            var configurationB = new PrimitivePropertyConfiguration();

            configurationB.IsNullable = false;

            var property = EdmProperty.Primitive("P", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));

            Assert.Null(property.GetConfiguration());

            configurationA.Configure(property);

            Assert.Equal(ConcurrencyMode.Fixed, ((PrimitivePropertyConfiguration)property.GetConfiguration()).ConcurrencyMode);

            configurationB.Configure(property);

            Assert.Equal(ConcurrencyMode.Fixed, ((PrimitivePropertyConfiguration)property.GetConfiguration()).ConcurrencyMode);
            Assert.Equal(false, ((PrimitivePropertyConfiguration)property.GetConfiguration()).IsNullable);
            Assert.Equal(GetConfigurationType(), property.GetConfiguration().GetType());
        }
Exemplo n.º 56
0
        public void Apply_MultiForeignKeysOnForeignKeyProperty_Works()
        {
            // Arrange
            Type dependentType        = typeof(MultiDependentEntity2);
            ODataModelBuilder builder = new ODataModelBuilder();

            builder.Entity <PrincipalEntity>().HasKey(p => new { p.PrincipalIntId, p.PrincipalStringId });

            EntityTypeConfiguration dependentEntity = builder.AddEntity(dependentType);

            PropertyInfo expectPropertyInfo1 = dependentType.GetProperty("PrincipalId1");
            PrimitivePropertyConfiguration propertyConfig1 = dependentEntity.AddProperty(expectPropertyInfo1);

            PropertyInfo expectPropertyInfo2 = dependentType.GetProperty("PrincipalId2");
            PrimitivePropertyConfiguration propertyConfig2 = dependentEntity.AddProperty(expectPropertyInfo2);

            PropertyInfo propertyInfo = dependentType.GetProperty("Principal");
            NavigationPropertyConfiguration navigation = dependentEntity.AddNavigationProperty(propertyInfo,
                                                                                               EdmMultiplicity.One);

            navigation.AddedExplicitly = false;

            // Act
            ForeignKeyAttributeConvention convention = new ForeignKeyAttributeConvention();

            convention.Apply(propertyConfig1, dependentEntity);
            convention.Apply(propertyConfig2, dependentEntity);

            // Assert
            Assert.Equal(2, navigation.DependentProperties.Count());
            Assert.Same(expectPropertyInfo1, navigation.DependentProperties.First());
            Assert.Same(expectPropertyInfo2, navigation.DependentProperties.Last());

            Assert.Equal(2, navigation.PrincipalProperties.Count());
            Assert.Equal("PrincipalIntId", navigation.PrincipalProperties.First().Name);
            Assert.Equal("PrincipalStringId", navigation.PrincipalProperties.Last().Name);
        }
Exemplo n.º 57
0
        /// <summary>
        /// Applies the configuration attributes for entities found in the specified assembly matching the given type filter
        /// </summary>
        /// <param name="modelBuilder">Model Builder</param>
        /// <param name="assembly">Assembly to search for entities</param>
        /// <param name="typeFilter">Filter for types in the given assembly</param>
        public static void ApplyConfigurationAttributes(this DbModelBuilder modelBuilder, Assembly assembly, Func <Type, bool> typeFilter)
        {
            foreach (Type classType in assembly.GetTypes().Where(t => t.IsClass && typeFilter(t)))
            {
                var propertiesToConfigure = classType
                                            .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                                            .Where(p => p.GetCustomAttribute <EFPropertyConfigurationAttribute>() != null)
                                            .Select(p => new { prop = p, attr = p.GetCustomAttribute <EFPropertyConfigurationAttribute>(true) });

                foreach (var propAttr in propertiesToConfigure)
                {
                    var entityConfig                     = modelBuilder.GetType().GetMethod("Entity").MakeGenericMethod(classType).Invoke(modelBuilder, null);
                    ParameterExpression param            = ParameterExpression.Parameter(classType, "c");
                    Expression          property         = Expression.Property(param, propAttr.prop.Name);
                    LambdaExpression    lambdaExpression = Expression.Lambda(property, true, new ParameterExpression[] { param });

                    MethodInfo methodInfo = entityConfig.GetType().GetMethod("Property", new[] { lambdaExpression.GetType() });
                    PrimitivePropertyConfiguration propertyConfig = methodInfo.Invoke(entityConfig, new[] { lambdaExpression })
                                                                    as PrimitivePropertyConfiguration;

                    propAttr.attr.Configure(propertyConfig);
                }
            }
        }
Exemplo n.º 58
0
        public void TimestampConvention_DoesntApplyWhenTheAttributeIsAppliedToMultipleProperties_InATypeHierarchy()
        {
            // Arrange
            PropertyInfo                   property       = CreateMockPropertyInfo("TestProperty");
            PropertyInfo                   otherProperty  = CreateMockPropertyInfo("OtherTestProperty");
            EntityTypeConfiguration        baseEntityType = new EntityTypeConfiguration();
            Mock <EntityTypeConfiguration> mockEntityType = new Mock <EntityTypeConfiguration>().SetupAllProperties();

            mockEntityType.Setup(c => c.BaseType).Returns(baseEntityType);
            mockEntityType.SetupGet(c => c.Kind).Returns(EdmTypeKind.Entity);

            EntityTypeConfiguration        entityType        = mockEntityType.Object;
            PrimitivePropertyConfiguration primitiveProperty = new PrimitivePropertyConfiguration(property, entityType);

            entityType.ExplicitProperties.Add(property, primitiveProperty);
            baseEntityType.ExplicitProperties.Add(otherProperty, new PrimitivePropertyConfiguration(otherProperty, baseEntityType));
            TimestampAttributeEdmPropertyConvention convention = new TimestampAttributeEdmPropertyConvention();

            // Act
            convention.Apply(primitiveProperty, entityType, new ODataConventionModelBuilder());

            // Assert
            Assert.False(primitiveProperty.ConcurrencyToken);
        }
Exemplo n.º 59
0
        public void TimestampConvention_DoesntApplyWhenTheAttributeIsAppliedToMultipleProperties_InATypeHierarchy()
        {
            // Arrange
            PropertyInfo            property       = CreateMockPropertyInfo("TestProperty");
            PropertyInfo            otherProperty  = CreateMockPropertyInfo("OtherTestProperty");
            ODataModelBuilder       modelBuilder   = ODataConventionModelBuilderFactory.Create();
            EntityTypeConfiguration baseEntityType = new EntityTypeConfiguration(modelBuilder, typeof(object));

            EntityTypeConfiguration entityType = new EntityTypeConfiguration(modelBuilder, typeof(Int32));

            entityType.BaseType = baseEntityType;

            PrimitivePropertyConfiguration primitiveProperty = new PrimitivePropertyConfiguration(property, entityType);

            entityType.ExplicitProperties.Add(property, primitiveProperty);
            baseEntityType.ExplicitProperties.Add(otherProperty, new PrimitivePropertyConfiguration(otherProperty, baseEntityType));
            TimestampAttributeEdmPropertyConvention convention = new TimestampAttributeEdmPropertyConvention();

            // Act
            convention.Apply(primitiveProperty, entityType, ODataConventionModelBuilderFactory.Create());

            // Assert
            Assert.False(primitiveProperty.ConcurrencyToken);
        }
Exemplo n.º 60
0
 public static void IsUnique(this PrimitivePropertyConfiguration property) => property
 .HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()
 {
     IsUnique = true
 }));