public void Apply_ignores_constraint_when_inverse_constraint_already_specified()
        {
            var mockTypeA = new MockType("A");
            var mockTypeB = new MockType("B").Property(mockTypeA, "A").Property<int>("AId1").Property<int>("AId2");
            mockTypeA.Property(mockTypeB, "B");

            var mockPropertyInfo = mockTypeA.GetProperty("B");
            var mockInversePropertyInfo = mockTypeB.GetProperty("A");

            var modelConfiguration = new ModelConfiguration();
            var navigationPropertyConfiguration
                = modelConfiguration.Entity(mockTypeA).Navigation(mockPropertyInfo);

            var inverseNavigationPropertyConfiguration
                = modelConfiguration.Entity(mockTypeB).Navigation(mockInversePropertyInfo);

            navigationPropertyConfiguration.InverseNavigationProperty = mockInversePropertyInfo;

            inverseNavigationPropertyConfiguration.Constraint
                = new ForeignKeyConstraintConfiguration(new[] { mockTypeB.GetProperty("AId1") });

            new ForeignKeyPrimitivePropertyAttributeConvention.ForeignKeyAttributeConventionImpl()
                .Apply(mockPropertyInfo, modelConfiguration, new ForeignKeyAttribute("AId2"));

            Assert.Null(navigationPropertyConfiguration.Constraint);
        }
        public void Apply_ignores_constraint_when_inverse_constraint_already_specified()
        {
            var mockTypeA = new MockType("A");
            var mockTypeB = new MockType("B").Property(mockTypeA, "A").Property <int>("AId1").Property <int>("AId2");

            mockTypeA.Property(mockTypeB, "B");

            var mockPropertyInfo        = mockTypeA.GetProperty("B");
            var mockInversePropertyInfo = mockTypeB.GetProperty("A");

            var modelConfiguration = new ModelConfiguration();
            var navigationPropertyConfiguration
                = modelConfiguration.Entity(mockTypeA).Navigation(mockPropertyInfo);

            var inverseNavigationPropertyConfiguration
                = modelConfiguration.Entity(mockTypeB).Navigation(mockInversePropertyInfo);

            navigationPropertyConfiguration.InverseNavigationProperty = mockInversePropertyInfo;

            inverseNavigationPropertyConfiguration.Constraint
                = new ForeignKeyConstraintConfiguration(new[] { mockTypeB.GetProperty("AId1") });

            new ForeignKeyPrimitivePropertyAttributeConvention()
            .Apply(mockPropertyInfo, modelConfiguration, new ForeignKeyAttribute("AId2"));

            Assert.Null(navigationPropertyConfiguration.Constraint);
        }
Beispiel #3
0
        public void RemoveBaseTypeProperties_RemovesAllBaseTypePropertiesFromDerivedTypes()
        {
            var mockType1 = new MockType("Foo").Property <int>("P1");
            var mockType2 = new MockType("Bar").BaseType(mockType1).Property <int>("P1").Property <int>("P2");
            var mockType3 = new MockType("FooBar").BaseType(mockType2).Property <int>("P1").Property <int>("P2");

            var mockAssembly = new MockAssembly(mockType1, mockType2, mockType3);

            HttpConfiguration configuration = new HttpConfiguration();

            configuration.Services.Replace(typeof(IAssembliesResolver), new TestAssemblyResolver(mockAssembly));
            var builder = new ODataConventionModelBuilder(configuration);

            var entity1 = builder.AddEntity(mockType1);

            entity1.AddProperty(mockType1.GetProperty("P1"));

            var entity2 = builder.AddEntity(mockType2).DerivesFrom(entity1);

            entity2.AddProperty(mockType2.GetProperty("P2"));

            var entity3 = builder.AddEntity(mockType3);

            entity3.AddProperty(mockType3.GetProperty("P1"));
            entity3.AddProperty(mockType3.GetProperty("P2"));

            builder.RemoveBaseTypeProperties(entity3, entity2);

            Assert.Empty(entity3.Properties);
        }
Beispiel #4
0
        public void Apply_adds_fk_column_when_nav_prop_is_valid()
        {
            var mockTypeA                  = new MockType("A");
            var mockTypeB                  = new MockType("B").Property <int>("AId").Property(mockTypeA, "A");
            var mockPropertyInfo           = mockTypeB.GetProperty("AId");
            var mockNavigationPropertyInfo = mockTypeB.GetProperty("A");

            var modelConfiguration = new ModelConfiguration();

            new ForeignKeyPrimitivePropertyAttributeConvention()
            .Apply(
                mockPropertyInfo,
                new ConventionTypeConfiguration(mockTypeB, () => modelConfiguration.Entity(mockTypeB), modelConfiguration),
                new ForeignKeyAttribute("A"));

            var navigationPropertyConfiguration
                = modelConfiguration.Entity(mockTypeB).Navigation(mockNavigationPropertyInfo);

            Assert.NotNull(navigationPropertyConfiguration.Constraint);

            var foreignKeyConstraint = (ForeignKeyConstraintConfiguration)navigationPropertyConfiguration.Constraint;

            Assert.Equal(new[] { mockTypeB.GetProperty("AId") }, foreignKeyConstraint.ToProperties);
            Assert.Null(navigationPropertyConfiguration.InverseNavigationProperty);
        }
Beispiel #5
0
        public void Apply_adds_fk_column_when_nav_prop_is_valid()
        {
            var mockTypeA = new MockType("A");
            var mockTypeB = new MockType("B").Property<int>("AId").Property(mockTypeA, "A");
            var mockPropertyInfo = mockTypeB.GetProperty("AId");
            var mockNavigationPropertyInfo = mockTypeB.GetProperty("A");

            var modelConfiguration = new ModelConfiguration();

            new ForeignKeyPrimitivePropertyAttributeConvention()
                .Apply(
                    mockPropertyInfo,
                    new ConventionTypeConfiguration(mockTypeB, () => modelConfiguration.Entity(mockTypeB), modelConfiguration),
                    new ForeignKeyAttribute("A"));

            var navigationPropertyConfiguration
                = modelConfiguration.Entity(mockTypeB).Navigation(mockNavigationPropertyInfo);

            Assert.NotNull(navigationPropertyConfiguration.Constraint);

            var foreignKeyConstraint = (ForeignKeyConstraintConfiguration)navigationPropertyConfiguration.Constraint;

            Assert.Equal(new[] { mockTypeB.GetProperty("AId") }, foreignKeyConstraint.ToProperties);
            Assert.Null(navigationPropertyConfiguration.InverseNavigationProperty);
        }
Beispiel #6
0
        public void Key_does_not_append_key_members_once_set_by_attributes()
        {
            var type = new MockType()
                       .Property <int>("Key1")
                       .Property <int>("Key2");
            var config = new EntityTypeConfiguration(type);

            config.Key(type.GetProperty("Key1"), null, true);
            config.Key(type.GetProperty("Key2"));

            Assert.Equal(1, config.KeyProperties.Count());
            Assert.Equal("Key1", config.KeyProperties.Single().Name);
        }
Beispiel #7
0
        public void Ctor_ThrowsArgument_IfMultiplicityIsManyAndPropertyIsNotCollection()
        {
            MockType mockEntity = new MockType().Property <int>("ID");

#if NETCOREAPP3_1
            ExceptionAssert.Throws <ArgumentException>(
                () => new NavigationPropertyConfiguration(mockEntity.GetProperty("ID"), EdmMultiplicity.Many, new EntityTypeConfiguration()),
                "The property 'ID' on the type 'T' is being configured as a Many-to-Many navigation property. Many to Many navigation properties must be collections. (Parameter 'property')");
#else
            ExceptionAssert.Throws <ArgumentException>(
                () => new NavigationPropertyConfiguration(mockEntity.GetProperty("ID"), EdmMultiplicity.Many, new EntityTypeConfiguration()),
                "The property 'ID' on the type 'T' is being configured as a Many-to-Many navigation property. Many to Many navigation properties must be collections.\r\nParameter name: property");
#endif
        }
Beispiel #8
0
        public void Key_appends_key_members_when_not_set_by_attributes()
        {
            var type = new MockType()
                       .Property <int>("Key1")
                       .Property <int>("Key2");
            var config = new EntityTypeConfiguration(type);

            config.Key(type.GetProperty("Key1"));
            config.Key(type.GetProperty("Key2"));

            Assert.Equal(2, config.KeyProperties.Count());
            Assert.Equal("Key1", config.KeyProperties.First().Name);
            Assert.Equal("Key2", config.KeyProperties.Last().Name);
        }
        public void Configure_should_uniquify_unconfigured_assocation_function_names()
        {
            var typeA = new MockType("A");
            var typeB = new MockType("B").Property(typeA.AsCollection(), "As");
            var mockPropertyInfo = typeB.GetProperty("As");
            typeA.Property(typeB.AsCollection(), "Bs");

            var modelConfiguration = new ModelConfiguration();

            var navigationPropertyConfiguration
                = modelConfiguration.Entity(typeB).Navigation(mockPropertyInfo);

            navigationPropertyConfiguration.ModificationFunctionsConfiguration
                = new ModificationFunctionsConfiguration();

            var modificationFunctionConfiguration = new ModificationFunctionConfiguration();
            modificationFunctionConfiguration.HasName("M2M_Delete");

            navigationPropertyConfiguration.ModificationFunctionsConfiguration
                .Insert(modificationFunctionConfiguration);

            var model = new EdmModel(DataSpace.CSpace);

            var entityA = model.AddEntityType("A");
            entityA.Annotations.SetClrType(typeA);
            entityA.SetConfiguration(modelConfiguration.Entity(typeA));

            var entityB = model.AddEntityType("B");
            entityB.Annotations.SetClrType(typeB);
            entityB.SetConfiguration(modelConfiguration.Entity(typeB));

            model.AddEntitySet("AS", entityA);
            model.AddEntitySet("BS", entityB);

            var associationType
                = model.AddAssociationType(
                    "M2M",
                    entityA,
                    RelationshipMultiplicity.Many,
                    entityB,
                    RelationshipMultiplicity.Many);

            associationType.SetConfiguration(navigationPropertyConfiguration);

            var navigationProperty
                = entityB.AddNavigationProperty("As", associationType);

            navigationProperty.SetClrPropertyInfo(mockPropertyInfo);

            model.AddAssociationSet("M2MSet", associationType);

            var databaseMapping
                = new DatabaseMappingGenerator(ProviderRegistry.Sql2008_ProviderManifest)
                    .Generate(model);

            modelConfiguration.Configure(databaseMapping, ProviderRegistry.Sql2008_ProviderManifest);

            Assert.True(databaseMapping.Database.Functions.Any(f => f.Name == "M2M_Delete"));
            Assert.True(databaseMapping.Database.Functions.Any(f => f.Name == "M2M_Delete1"));
        }
Beispiel #10
0
        public void Apply_AliasSetIfEnabled_ValidPropertyAlias(string propertyAlias, bool modelAliasing, string expectedProptertyName)
        {
            // Arrange
            ODataConventionModelBuilder modelBuilder = new ODataConventionModelBuilder()
            {
                ModelAliasingEnabled = modelAliasing
            };

            MockType type =
                new MockType("Mocktype")
                .Property(typeof(string), "Property", new[] { new DataMemberAttribute {
                                                                  Name = propertyAlias
                                                              } });

            type.Setup(t => t.GetCustomAttributes(It.IsAny <Type>(), It.IsAny <bool>())).Returns(new[] { new DataContractAttribute() });

            Mock <StructuralTypeConfiguration> structuralType = new Mock <StructuralTypeConfiguration>();

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

            PropertyInfo property = type.GetProperty("Property");
            Mock <StructuralPropertyConfiguration> structuralProperty = new Mock <StructuralPropertyConfiguration>(property, structuralType.Object);

            structuralProperty.Object.AddedExplicitly = false;

            // Act
            new DataMemberAttributeEdmPropertyConvention().Apply(structuralProperty.Object, structuralType.Object, modelBuilder);

            // Assert
            Assert.Equal(expectedProptertyName, structuralProperty.Object.Name);
        }
        public void Apply_AliasNotSet_NoPropertyAlias(bool modelAliasing)
        {
            // Arrange
            ODataConventionModelBuilder modelBuilder = ODataConventionModelBuilderHelper.CreateWithModelAliasing(modelAliasing: modelAliasing);

            MockType type =
                new MockType("Mocktype")
                .Property(typeof(string), "Property", new[] { new DataMemberAttribute() });

            type.Setup(t => t.GetCustomAttributes(It.IsAny <Type>(), It.IsAny <bool>())).Returns(new[] { new DataContractAttribute() });

            Mock <StructuralTypeConfiguration> structuralType = new Mock <StructuralTypeConfiguration>();

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

            PropertyInfo property = type.GetProperty("Property");
            Mock <StructuralPropertyConfiguration> structuralProperty = new Mock <StructuralPropertyConfiguration>(property, structuralType.Object);

            structuralProperty.Object.AddedExplicitly = false;

            // Act
            new DataMemberAttributeEdmPropertyConvention().Apply(structuralProperty.Object, structuralType.Object, modelBuilder);

            // Assert
            Assert.Equal("Property", structuralProperty.Object.Name);
        }
        public void Apply_SetsTimeSpanProperty_AsEdmTimeOfDay(string typeName, bool expect)
        {
            // Arrange
            MockType type = new MockType("Customer")
                .Property(typeof(TimeSpan), "CreatedTime", new[] {new ColumnAttribute {TypeName = typeName}});

            Mock<StructuralTypeConfiguration> structuralType = new Mock<StructuralTypeConfiguration>();
            structuralType.Setup(t => t.ClrType).Returns(type);

            PropertyInfo property = type.GetProperty("CreatedTime");
            Mock<PrimitivePropertyConfiguration> primitiveProperty = new Mock<PrimitivePropertyConfiguration>(property, structuralType.Object);
            primitiveProperty.Setup(p => p.RelatedClrType).Returns(typeof(TimeSpan));
            primitiveProperty.Object.AddedExplicitly = false;

            // Act
            new ColumnAttributeEdmPropertyConvention().Apply(primitiveProperty.Object, structuralType.Object,
                new ODataConventionModelBuilder());

            // Assert
            if (expect)
            {
                Assert.NotNull(primitiveProperty.Object.TargetEdmTypeKind);
                Assert.Equal(EdmPrimitiveTypeKind.TimeOfDay, primitiveProperty.Object.TargetEdmTypeKind);
            }
            else
            {
                Assert.Null(primitiveProperty.Object.TargetEdmTypeKind);
            }
        }
Beispiel #13
0
        public void DerivedType_DataMemberRequired_IsHonored_IfDerivedtypeIsDataContract()
        {
            // Arrange
            MockType baseType = new MockType("BaseMocktype");

            baseType.Setup(t => t.GetCustomAttributes(It.IsAny <Type>(), It.IsAny <bool>())).Returns(new[] { new DataContractAttribute() });

            MockType derivedType =
                new MockType("DerivedMockType")
                .Property(typeof(int), "Property", new[] { new DataMemberAttribute {
                                                               IsRequired = true
                                                           } })
                .BaseType(baseType);

            PropertyInfo property = derivedType.GetProperty("Property");
            Mock <IStructuralTypeConfiguration>    structuralType     = new Mock <IStructuralTypeConfiguration>();
            Mock <StructuralPropertyConfiguration> structuralProperty = new Mock <StructuralPropertyConfiguration>(property, structuralType.Object);

            structuralType.Setup(t => t.ClrType).Returns(derivedType);

            // Act
            new DataMemberAttributeEdmPropertyConvention().Apply(structuralProperty.Object, structuralType.Object);

            // Assert
            Assert.False(structuralProperty.Object.OptionalProperty);
        }
        public void ConcurrencyCheckAttributeEdmPropertyConvention_DoesnotOverwriteExistingConfiguration()
        {
            // Arrange
            MockType type =
                new MockType("Entity")
                .Property(typeof(int), "ID")
                .Property(typeof(int), "Count", new ConcurrencyCheckAttribute());

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var entityType = builder.AddEntityType(type);

            entityType.AddProperty(type.GetProperty("Count")).IsOptional();
            builder.AddEntitySet("EntitySet", entityType);

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

            // Assert
            IEdmEntityType         entity   = model.AssertHasEntityType(type);
            IEdmStructuralProperty property = entity.AssertHasPrimitiveProperty(
                model,
                "Count",
                EdmPrimitiveTypeKind.Int32,
                isNullable: true);

            IEdmEntitySet entitySet = model.EntityContainer.FindEntitySet("EntitySet");

            Assert.NotNull(entitySet);

            IEnumerable <IEdmStructuralProperty> currencyProperties = model.GetConcurrencyProperties(entitySet);
            IEdmStructuralProperty currencyProperty = Assert.Single(currencyProperties);

            Assert.Same(property, currencyProperty);
        }
        public void Apply_SetsTimeSpanProperty_AsEdmTimeOfDay(string typeName, bool expect)
        {
            // Arrange
            MockType type = new MockType("Customer")
                            .Property(typeof(TimeSpan), "CreatedTime", new[] { new ColumnAttribute {
                                                                                   TypeName = typeName
                                                                               } });

            Mock <StructuralTypeConfiguration> structuralType = new Mock <StructuralTypeConfiguration>();

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

            PropertyInfo property = type.GetProperty("CreatedTime");
            Mock <PrimitivePropertyConfiguration> primitiveProperty = new Mock <PrimitivePropertyConfiguration>(property, structuralType.Object);

            primitiveProperty.Setup(p => p.RelatedClrType).Returns(typeof(TimeSpan));
            primitiveProperty.Object.AddedExplicitly = false;

            // Act
            new ColumnAttributeEdmPropertyConvention().Apply(primitiveProperty.Object, structuralType.Object,
                                                             ODataConventionModelBuilderFactory.Create());

            // Assert
            if (expect)
            {
                Assert.NotNull(primitiveProperty.Object.TargetEdmTypeKind);
                Assert.Equal(EdmPrimitiveTypeKind.TimeOfDay, primitiveProperty.Object.TargetEdmTypeKind);
            }
            else
            {
                Assert.Null(primitiveProperty.Object.TargetEdmTypeKind);
            }
        }
Beispiel #16
0
        public void DatabaseGeneratedAttributeEdmPropertyConvention_DoesnotOverwriteExistingConfiguration()
        {
            // Arrange
            MockType type =
                new MockType("Entity")
                .Property(typeof(int), "ID")
                .Property(typeof(int?), "Count", new DatabaseGeneratedAttribute(DatabaseGeneratedOption.Computed));

            // Act
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

            builder.AddEntity(type).AddProperty(type.GetProperty("Count")).IsOptional();
            IEdmModel model = builder.GetEdmModel();

            // Assert
            IEdmEntityType         entity   = model.AssertHasEntityType(type);
            IEdmStructuralProperty property = entity.AssertHasPrimitiveProperty(model, "Count",
                                                                                EdmPrimitiveTypeKind.Int32, isNullable: true);

            var idAnnotation = model.GetAnnotationValue <EdmStringConstant>(
                property,
                StoreGeneratedPatternAnnotation.AnnotationsNamespace,
                "StoreGeneratedPattern");

            Assert.Null(idAnnotation);
        }
        public void Apply_DoesnotSetRequiredProperty_IfTypeIsNotADataContract()
        {
            // Arrange
            MockType type =
                new MockType("Mocktype")
                .Property(typeof(string), "Property", new[] { new DataMemberAttribute {
                                                                  IsRequired = true
                                                              } });

            type.Setup(t => t.GetCustomAttributes(It.IsAny <Type>(), It.IsAny <bool>())).Returns(new object[0]);

            Mock <StructuralTypeConfiguration> structuralType = new Mock <StructuralTypeConfiguration>();

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

            PropertyInfo property = type.GetProperty("Property");
            Mock <StructuralPropertyConfiguration> structuralProperty = new Mock <StructuralPropertyConfiguration>(property, structuralType.Object);

            structuralProperty.Object.AddedExplicitly = false;

            // Act
            new DataMemberAttributeEdmPropertyConvention().Apply(structuralProperty.Object, structuralType.Object, ODataConventionModelBuilderFactory.Create());

            // Assert
            Assert.True(structuralProperty.Object.OptionalProperty);
        }
        public void Ctor_ThrowsArgument_IfMultiplicityIsManyAndPropertyIsNotCollection()
        {
            MockType mockEntity = new MockType().Property<int>("ID");

            Assert.Throws<ArgumentException>(
                () => new NavigationPropertyConfiguration(mockEntity.GetProperty("ID"), EdmMultiplicity.Many, new EntityTypeConfiguration()),
                "The property 'ID' on the type 'T' is being configured as a Many-to-Many navigation property. Many to Many navigation properties must be collections.\r\nParameter name: property");
        }
Beispiel #19
0
        public void Apply_ignores_inverse_when_already_configured()
        {
            var mockTypeA = new MockType("A");
            var mockTypeB = new MockType("B").Property(mockTypeA, "A1").Property(mockTypeA, "A2");

            mockTypeA.Property(mockTypeB, "B");
            var mockPropertyInfo   = mockTypeA.GetProperty("B");
            var modelConfiguration = new ModelConfiguration();
            var navigationPropertyConfiguration
                = modelConfiguration.Entity(mockTypeA).Navigation(mockPropertyInfo);

            navigationPropertyConfiguration.InverseNavigationProperty = mockTypeB.GetProperty("A2");

            new InversePropertyAttributeConvention()
            .Apply(mockPropertyInfo, modelConfiguration, new InversePropertyAttribute("A1"));

            Assert.NotSame(mockTypeB.GetProperty("A1"), navigationPropertyConfiguration.InverseNavigationProperty);
        }
        public void Apply_ignores_constraint_when_already_specified()
        {
            var mockTypeA = new MockType("A");
            var mockTypeB = new MockType("B").Property<int>("AId1").Property<int>("AId2");
            mockTypeA.Property(mockTypeB, "B");
            var mockPropertyInfo = mockTypeA.GetProperty("B");
            var modelConfiguration = new ModelConfiguration();
            var navigationPropertyConfiguration
                = modelConfiguration.Entity(mockTypeA).Navigation(mockPropertyInfo);
            navigationPropertyConfiguration.Constraint
                = new ForeignKeyConstraintConfiguration(new[] { mockTypeB.GetProperty("AId1") });

            new ForeignKeyPrimitivePropertyAttributeConvention.ForeignKeyAttributeConventionImpl()
                .Apply(mockPropertyInfo, modelConfiguration, new ForeignKeyAttribute("AId2"));

            var foreignKeyConstraint = (ForeignKeyConstraintConfiguration)navigationPropertyConfiguration.Constraint;

            Assert.Equal(new[] { mockTypeB.GetProperty("AId1") }, foreignKeyConstraint.DependentProperties);
        }
Beispiel #21
0
        public void IsKey_is_noop_when_set()
        {
            var type = new MockType()
                       .Property <int>("Property1")
                       .Property <int>("Property2");
            var typeConfig = new EntityTypeConfiguration(type);

            typeConfig.Key(new[] { type.GetProperty("Property1") });
            var innerConfig = new PrimitivePropertyConfiguration
            {
                TypeConfiguration = typeConfig
            };
            var propertyInfo = type.GetProperty("Property2");
            var config       = new LightweightPropertyConfiguration(propertyInfo, () => innerConfig);

            var result = config.IsKey();

            Assert.DoesNotContain(propertyInfo, typeConfig.KeyProperties);
            Assert.Same(config, result);
        }
        public void Apply_ignores_constraint_when_already_specified()
        {
            var mockTypeA = new MockType("A");
            var mockTypeB = new MockType("B").Property <int>("AId1").Property <int>("AId2");

            mockTypeA.Property(mockTypeB, "B");
            var mockPropertyInfo   = mockTypeA.GetProperty("B");
            var modelConfiguration = new ModelConfiguration();
            var navigationPropertyConfiguration
                = modelConfiguration.Entity(mockTypeA).Navigation(mockPropertyInfo);

            navigationPropertyConfiguration.Constraint
                = new ForeignKeyConstraintConfiguration(new[] { mockTypeB.GetProperty("AId1") });

            new ForeignKeyPrimitivePropertyAttributeConvention()
            .Apply(mockPropertyInfo, modelConfiguration, new ForeignKeyAttribute("AId2"));

            var foreignKeyConstraint = (ForeignKeyConstraintConfiguration)navigationPropertyConfiguration.Constraint;

            Assert.Equal(new[] { mockTypeB.GetProperty("AId1") }, foreignKeyConstraint.ToProperties);
        }
Beispiel #23
0
        public void Mapping_a_single_abstract_type_should_not_throw()
        {
            var modelConfiguration = new ModelConfiguration();
            var mockType           = new MockType("T").TypeAttributes(TypeAttributes.Abstract).Property <int>("Id");

            modelConfiguration.Entity(mockType).Key(mockType.GetProperty("Id"));
            var modelBuilder = new DbModelBuilder();

            var databaseMapping = modelBuilder.Build(ProviderRegistry.Sql2008_ProviderInfo);

            Assert.NotNull(databaseMapping);
        }
        public void Apply_throws_when_cannot_find_navigation_property()
        {
            var mockTypeA = new MockType("A");

            mockTypeA.Property(typeof(int), "BId");
            var mockPropertyInfo = mockTypeA.GetProperty("BId");

            Assert.Equal(
                Strings.ForeignKeyAttributeConvention_InvalidNavigationProperty("BId", mockTypeA.Object, "Missing"),
                Assert.Throws <InvalidOperationException>(
                    () => new ForeignKeyPrimitivePropertyAttributeConvention()
                    .Apply(mockPropertyInfo, new ModelConfiguration(), new ForeignKeyAttribute("Missing"))).Message);
        }
        public void RequiredAttributeEdmPropertyConvention_DoesnotOverwriteExistingConfiguration()
        {
            MockType type =
                new MockType("Entity")
                .Property(typeof(int), "ID")
                .Property(typeof(int), "Count", new RequiredAttribute());

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.AddEntityType(type).AddProperty(type.GetProperty("Count")).IsOptional();

            IEdmModel model = builder.GetEdmModel();
            IEdmEntityType entity = model.AssertHasEntityType(type);
            entity.AssertHasPrimitiveProperty(model, "Count", EdmPrimitiveTypeKind.Int32, isNullable: true);
        }
        public void Apply_ignores_inverse_on_nonnavigation()
        {
            var mockTypeA           = new MockType("A").Property(typeof(int), "B");
            var mockPropertyInfo    = mockTypeA.GetProperty("B");
            var modelConfiguration  = new ModelConfiguration();
            var entityConfiguration = modelConfiguration.Entity(mockTypeA);

            new InversePropertyAttributeConvention()
            .Apply(
                mockPropertyInfo, new ConventionTypeConfiguration(mockTypeA, () => entityConfiguration, modelConfiguration),
                new InversePropertyAttribute("A1"));

            Assert.False(entityConfiguration.IsNavigationPropertyConfigured(mockPropertyInfo));
        }
Beispiel #27
0
        public void Apply_throws_on_self_inverse()
        {
            var mockTypeA = new MockType("A");

            mockTypeA.Property(mockTypeA, "A");
            var mockPropertyInfo   = mockTypeA.GetProperty("A");
            var modelConfiguration = new ModelConfiguration();

            Assert.Equal(
                Strings.InversePropertyAttributeConvention_SelfInverseDetected("A", mockTypeA.Object),
                Assert.Throws <InvalidOperationException>(
                    () => new InversePropertyAttributeConvention()
                    .Apply(mockPropertyInfo, modelConfiguration, new InversePropertyAttribute("A"))).Message);
        }
        public void AsDate_ThrowsArgument(Type propertyType)
        {
            // Arrange
            MockType type = new MockType().Property(propertyType, "Birthday");
            PropertyInfo property = type.GetProperty("Birthday");
            _structuralType.Setup(t => t.ClrType).Returns(type);

            // Act
            PrimitivePropertyConfiguration propertyConfig = new PrimitivePropertyConfiguration(property, _structuralType.Object);

            // Assert
            Assert.ThrowsArgument(() => propertyConfig.AsDate(), "property",
                "The property 'Birthday' on type 'NS.Customer' must be a System.DateTime property");
        }
        public void AsTimeOfDay_ThrowsArgument(Type propertyType)
        {
            // Arrange
            MockType     type     = new MockType().Property(propertyType, "CreatedTime");
            PropertyInfo property = type.GetProperty("CreatedTime");

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

            // Act
            PrimitivePropertyConfiguration propertyConfig = new PrimitivePropertyConfiguration(property, _structuralType.Object);

            // Assert
            ExceptionAssert.ThrowsArgument(() => propertyConfig.AsTimeOfDay(), "property",
                                           "The property 'CreatedTime' on type 'NS.Customer' must be a System.TimeSpan property");
        }
Beispiel #30
0
        public void Apply_throws_when_cannot_find_inverse_property()
        {
            var mockTypeA = new MockType("A");
            var mockTypeB = new MockType("B");

            mockTypeA.Property(mockTypeB, "B");
            var mockPropertyInfo   = mockTypeA.GetProperty("B");
            var modelConfiguration = new ModelConfiguration();

            Assert.Equal(
                Strings.InversePropertyAttributeConvention_PropertyNotFound("Foo", mockTypeB.Object, "B", mockTypeA.Object),
                Assert.Throws <InvalidOperationException>(
                    () => new InversePropertyAttributeConvention()
                    .Apply(mockPropertyInfo, modelConfiguration, new InversePropertyAttribute("Foo"))).Message);
        }
Beispiel #31
0
        public void AsDate_ThrowsArgument(Type propertyType)
        {
            // Arrange
            MockType     type     = new MockType().Property(propertyType, "Birthday");
            PropertyInfo property = type.GetProperty("Birthday");

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

            // Act
            PrimitivePropertyConfiguration propertyConfig = new PrimitivePropertyConfiguration(property, _structuralType.Object);

            // Assert
            Assert.ThrowsArgument(() => propertyConfig.AsDate(), "property",
                                  "The property 'Birthday' on type 'NS.Customer' must be a System.DateTime property");
        }
        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);
        }
Beispiel #33
0
        public void Build_should_map_types()
        {
            var modelConfiguration = new ModelConfiguration();
            var mockType           = new MockType("T").Property <int>("Id");

            modelConfiguration.Entity(mockType).Key(mockType.GetProperty("Id"));
            modelConfiguration.ComplexType(new MockType("C"));
            var modelBuilder = new DbModelBuilder(modelConfiguration);

            var databaseMapping = modelBuilder.Build(ProviderRegistry.Sql2008_ProviderInfo).DatabaseMapping;

            Assert.NotNull(databaseMapping);
            Assert.Equal(1, databaseMapping.Model.GetEntityTypes().Count());
            Assert.Equal(1, databaseMapping.Model.GetComplexTypes().Count());
        }
        public void HasKey_is_noop_when_set()
        {
            var type = new MockType()
                       .Property <int>("Property1")
                       .Property <int>("Property2");
            var innerConfig = new EntityTypeConfiguration(type);

            innerConfig.Key(new[] { type.GetProperty("Property1") });
            var config = new LightweightEntityConfiguration(type, () => innerConfig);

            var result = config.HasKey("Property2");

            Assert.Equal(1, innerConfig.KeyProperties.Count());
            Assert.False(innerConfig.KeyProperties.Any(p => p.Name == "Property2"));
            Assert.Same(config, result);
        }
        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);
        }
        public void RequiredAttributeEdmPropertyConvention_DoesnotOverwriteExistingConfiguration()
        {
            MockType type =
                new MockType("Entity")
                .Property(typeof(int), "ID")
                .Property(typeof(int), "Count", new RequiredAttribute());

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

            builder.AddEntity(type).AddProperty(type.GetProperty("Count")).IsOptional();

            IEdmModel      model  = builder.GetEdmModel();
            IEdmEntityType entity = model.AssertHasEntityType(type);

            entity.AssertHasPrimitiveProperty(model, "Count", EdmPrimitiveTypeKind.Int32, isNullable: true);
        }
Beispiel #37
0
        public void Build_should_apply_model_configuration()
        {
            var modelConfiguration = new ModelConfiguration();
            var mockType           = new MockType("T").Property <int>("Id");

            modelConfiguration.Entity(mockType)
            .Property(new PropertyPath(mockType.GetProperty("Id")))
            .ConcurrencyMode = ConcurrencyMode.Fixed;

            var databaseMapping = new DbModelBuilder(modelConfiguration).Build(ProviderRegistry.Sql2008_ProviderInfo).DatabaseMapping;

            Assert.NotNull(databaseMapping);
            Assert.Equal(
                ConcurrencyMode.Fixed,
                databaseMapping.Model.Namespaces.Single().EntityTypes.Single().DeclaredProperties.Single().ConcurrencyMode);
        }
        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);
        }
        public void Apply_finds_inverse_when_many_to_many()
        {
            var mockTypeA = new MockType("A");
            var mockTypeB = new MockType("B").Property(mockTypeA.AsCollection(), "As");
            var mockPropertyInfo = mockTypeB.GetProperty("As");
            mockTypeA.Property(mockTypeB.AsCollection(), "Bs");
            var modelConfiguration = new ModelConfiguration();

            new InversePropertyAttributeConvention()
                .Apply(mockPropertyInfo, modelConfiguration, new InversePropertyAttribute("Bs"));

            var navigationPropertyConfiguration
                = modelConfiguration.Entity(mockTypeB).Navigation(mockPropertyInfo);

            Assert.Same(mockTypeA.GetProperty("Bs"), navigationPropertyConfiguration.InverseNavigationProperty);
        }
Beispiel #40
0
        public void Apply_finds_inverse_when_many_to_many()
        {
            var mockTypeA        = new MockType("A");
            var mockTypeB        = new MockType("B").Property(mockTypeA.AsCollection(), "As");
            var mockPropertyInfo = mockTypeB.GetProperty("As");

            mockTypeA.Property(mockTypeB.AsCollection(), "Bs");
            var modelConfiguration = new ModelConfiguration();

            new InversePropertyAttributeConvention()
            .Apply(mockPropertyInfo, modelConfiguration, new InversePropertyAttribute("Bs"));

            var navigationPropertyConfiguration
                = modelConfiguration.Entity(mockTypeB).Navigation(mockPropertyInfo);

            Assert.Same(mockTypeA.GetProperty("Bs"), navigationPropertyConfiguration.InverseNavigationProperty);
        }
        public void Apply_DoesnotSetRequiredProperty_IfTypeIsNotADataContract()
        {
            // Arrange
            MockType type =
                new MockType("Mocktype")
                .Property(typeof(string), "Property", new[] { new DataMemberAttribute { IsRequired = true } });
            type.Setup(t => t.GetCustomAttributes(It.IsAny<Type>(), It.IsAny<bool>())).Returns(new object[0]);

            PropertyInfo property = type.GetProperty("Property");
            Mock<StructuralTypeConfiguration> structuralType = new Mock<StructuralTypeConfiguration>();
            Mock<StructuralPropertyConfiguration> structuralProperty = new Mock<StructuralPropertyConfiguration>(property, structuralType.Object);
            structuralType.Setup(t => t.ClrType).Returns(type);

            // Act
            new DataMemberAttributeEdmPropertyConvention().Apply(structuralProperty.Object, structuralType.Object);

            // Assert
            Assert.True(structuralProperty.Object.OptionalProperty);
        }
        public void ConcurrencyCheckAttributeEdmPropertyConvention_DoesnotOverwriteExistingConfiguration()
        {
            MockType type =
                new MockType("Entity")
                .Property(typeof(int), "ID")
                .Property(typeof(int), "Count", new ConcurrencyCheckAttribute());

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.AddEntityType(type).AddProperty(type.GetProperty("Count")).IsOptional();

            IEdmModel model = builder.GetEdmModel();
            IEdmEntityType entity = model.AssertHasEntityType(type);
            IEdmStructuralProperty property = entity.AssertHasPrimitiveProperty(
                model,
                "Count",
                EdmPrimitiveTypeKind.Int32,
                isNullable: true);
            Assert.Equal(EdmConcurrencyMode.Fixed, property.ConcurrencyMode);
        }
Beispiel #43
0
        public void Apply_finds_inverse_when_optional_to_optional()
        {
            var mockTypeA = new MockType("A");
            var mockTypeB = new MockType("B").Property(mockTypeA, "A");
            var mockPropertyInfo = mockTypeB.GetProperty("A");
            mockTypeA.Property(mockTypeB, "B");
            var modelConfiguration = new ModelConfiguration();

            new InversePropertyAttributeConvention()
                .Apply(
                    mockPropertyInfo,
                    new ConventionTypeConfiguration(mockTypeB, () => modelConfiguration.Entity(mockTypeB), modelConfiguration),
                    new InversePropertyAttribute("B"));

            var navigationPropertyConfiguration
                = modelConfiguration.Entity(mockTypeB).Navigation(mockPropertyInfo);

            Assert.Same(mockTypeA.GetProperty("B"), navigationPropertyConfiguration.InverseNavigationProperty);
        }
        public void Apply_SetsRequiredProperty()
        {
            // Arrange
            MockType type =
                new MockType("Mocktype")
                .Property(typeof(string), "Property", new[] { new DataMemberAttribute { IsRequired = true } });
            type.Setup(t => t.GetCustomAttributes(It.IsAny<Type>(), It.IsAny<bool>())).Returns(new[] { new DataContractAttribute() });

            Mock<StructuralTypeConfiguration> structuralType = new Mock<StructuralTypeConfiguration>();
            structuralType.Setup(t => t.ClrType).Returns(type);

            PropertyInfo property = type.GetProperty("Property");
            Mock<StructuralPropertyConfiguration> structuralProperty = new Mock<StructuralPropertyConfiguration>(property, structuralType.Object);
            structuralProperty.Object.AddedExplicitly = false;

            // Act
            new DataMemberAttributeEdmPropertyConvention().Apply(structuralProperty.Object, structuralType.Object, new ODataConventionModelBuilder());

            // Assert
            Assert.False(structuralProperty.Object.OptionalProperty);
        }
        public void DatabaseGeneratedAttributeEdmPropertyConvention_DoesnotOverwriteExistingConfiguration()
        {
            // Arrange
            MockType type =
                new MockType("Entity")
                .Property(typeof(int), "ID")
                .Property(typeof(int?), "Count", new DatabaseGeneratedAttribute(DatabaseGeneratedOption.Computed));

            // Act
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.AddEntity(type).AddProperty(type.GetProperty("Count")).IsOptional();
            IEdmModel model = builder.GetEdmModel();

            // Assert
            IEdmEntityType entity = model.AssertHasEntityType(type);
            IEdmStructuralProperty property = entity.AssertHasPrimitiveProperty(model, "Count",
                EdmPrimitiveTypeKind.Int32, isNullable: true);

            var idAnnotation = model.GetAnnotationValue<EdmStringConstant>(
                property,
                StoreGeneratedPatternAnnotation.AnnotationsNamespace,
                "StoreGeneratedPattern");
            Assert.Null(idAnnotation);
        }
        public void Apply_ignores_inverse_when_already_configured()
        {
            var mockTypeA = new MockType("A");
            var mockTypeB = new MockType("B").Property(mockTypeA, "A1").Property(mockTypeA, "A2");
            mockTypeA.Property(mockTypeB, "B");
            var mockPropertyInfo = mockTypeA.GetProperty("B");
            var modelConfiguration = new ModelConfiguration();
            var navigationPropertyConfiguration
                = modelConfiguration.Entity(mockTypeA).Navigation(mockPropertyInfo);
            navigationPropertyConfiguration.InverseNavigationProperty = mockTypeB.GetProperty("A2");

            new InversePropertyAttributeConvention()
                .Apply(mockPropertyInfo, modelConfiguration, new InversePropertyAttribute("A1"));

            Assert.NotSame(mockTypeB.GetProperty("A1"), navigationPropertyConfiguration.InverseNavigationProperty);
        }
        public void CanMapObjectArrayAsAComplexProperty()
        {
            MockType type =
                new MockType("entity")
                .Property<int>("ID")
                .Property<object[]>("Collection");

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var entityType = builder.AddEntity(type);
            entityType.AddCollectionProperty(type.GetProperty("Collection"));
            builder.AddEntitySet("entityset", entityType);

            IEdmModel model = builder.GetEdmModel();
            Assert.Equal(3, model.SchemaElements.Count());
            var entityEdmType = model.AssertHasEntitySet("entityset", type);
            model.AssertHasComplexType(typeof(object));
            entityEdmType.AssertHasCollectionProperty(model, "Collection", typeof(object), isNullable: true);
        }
        public void Apply_throws_when_cannot_find_inverse_property()
        {
            var mockTypeA = new MockType("A");
            var mockTypeB = new MockType("B");
            mockTypeA.Property(mockTypeB, "B");
            var mockPropertyInfo = mockTypeA.GetProperty("B");
            var modelConfiguration = new ModelConfiguration();

            Assert.Equal(
                Strings.InversePropertyAttributeConvention_PropertyNotFound("Foo", mockTypeB.Object, "B", mockTypeA.Object),
                Assert.Throws<InvalidOperationException>(
                    () => new InversePropertyAttributeConvention()
                              .Apply(mockPropertyInfo, modelConfiguration, new InversePropertyAttribute("Foo"))).Message);
        }
        public void Apply_throws_on_self_inverse()
        {
            var mockTypeA = new MockType("A");
            mockTypeA.Property(mockTypeA, "A");
            var mockPropertyInfo = mockTypeA.GetProperty("A");
            var modelConfiguration = new ModelConfiguration();

            Assert.Equal(
                Strings.InversePropertyAttributeConvention_SelfInverseDetected("A", mockTypeA.Object),
                Assert.Throws<InvalidOperationException>(
                    () => new InversePropertyAttributeConvention()
                              .Apply(mockPropertyInfo, modelConfiguration, new InversePropertyAttribute("A"))).Message);
        }
        public void HasKey_composite_is_noop_when_set()
        {
            var type = new MockType()
                .Property<int>("Property1")
                .Property<int>("Property2")
                .Property<int>("Property3");
            var innerConfig = new EntityTypeConfiguration(type);
            innerConfig.Key(new[] { type.GetProperty("Property1") });
            var config = new LightweightEntityConfiguration(type, () => innerConfig);

            var result = config.HasKey(new[] { "Property2", "Property3" });

            Assert.Equal(1, innerConfig.KeyProperties.Count());
            Assert.False(innerConfig.KeyProperties.Any(p => p.Name == "Property2"));
            Assert.False(innerConfig.KeyProperties.Any(p => p.Name == "Property3"));
            Assert.Same(config, result);
        }
        public void Apply_AliasSetIfEnabled_ValidPropertyAlias(string propertyAlias, bool modelAliasing, string expectedProptertyName)
        {
            // Arrange
            MockType type =
                new MockType("Mocktype")
                .Property(typeof(string), "Property", new[] { new DataMemberAttribute { Name = propertyAlias } });
            type.Setup(t => t.GetCustomAttributes(It.IsAny<Type>(), It.IsAny<bool>())).Returns(new[] { new DataContractAttribute() });

            PropertyInfo property = type.GetProperty("Property");
            Mock<StructuralTypeConfiguration> structuralType = new Mock<StructuralTypeConfiguration>();
            ODataModelBuilder modelBuilder = new ODataModelBuilder { ModelAliasingEnabled = modelAliasing };
            structuralType.SetupGet(s => s.ModelBuilder).Returns(modelBuilder);
            Mock<StructuralPropertyConfiguration> structuralProperty = new Mock<StructuralPropertyConfiguration>(property, structuralType.Object);
            structuralProperty.Object.AddedExplicitly = false;
            structuralType.Setup(t => t.ClrType).Returns(type);

            // Act
            new DataMemberAttributeEdmPropertyConvention().Apply(structuralProperty.Object, structuralType.Object);

            // Assert
            Assert.Equal(expectedProptertyName, structuralProperty.Object.Name);
        }
        public void DataMemberAttributeEdmPropertyConvention_DoesnotOverwriteExistingConfiguration()
        {
            MockType type =
                new MockType("Entity")
                .Property(typeof(int), "ID", new DataMemberAttribute())
                .Property(typeof(int), "Count", new DataMemberAttribute { IsRequired = true });
            type.Setup(t => t.GetCustomAttributes(It.IsAny<Type>(), It.IsAny<bool>())).Returns(new[] { new DataContractAttribute() });

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.AddEntity(type).AddProperty(type.GetProperty("Count")).IsOptional();

            IEdmModel model = builder.GetEdmModel();
            IEdmEntityType entity = model.AssertHasEntityType(type);
            entity.AssertHasPrimitiveProperty(model, "Count", EdmPrimitiveTypeKind.Int32, isNullable: true);
        }
        public void IgnoredPropertyOnBaseType_DoesnotShowupOnDerivedType()
        {
            // Arrange
            var baseType =
                new MockType("BaseType")
                .Property<int>("BaseTypeProperty");

            var derivedType =
                new MockType("DerivedType")
                .BaseType(baseType)
                .Property<int>("DerivedTypeProperty");

            var mockAssembly = new MockAssembly(baseType, derivedType);

            HttpConfiguration configuration = new HttpConfiguration();
            configuration.Services.Replace(typeof(IAssembliesResolver), new TestAssemblyResolver(mockAssembly));
            var builder = new ODataConventionModelBuilder(configuration);

            // Act
            var baseEntity = builder.AddEntity(baseType);
            baseEntity.RemoveProperty(baseType.GetProperty("BaseTypeProperty"));
            IEdmModel model = builder.GetEdmModel();

            // Assert
            IEdmEntityType baseEntityType = model.AssertHasEntityType(derivedType);
            Assert.DoesNotContain("BaseTypeProperty", baseEntityType.Properties().Select(p => p.Name));
            IEdmEntityType derivedEntityType = model.AssertHasEntityType(derivedType);
            Assert.DoesNotContain("BaseTypeProperty", derivedEntityType.Properties().Select(p => p.Name));
        }
        public void ModelBuilder_Doesnot_Override_NavigationPropertyConfiguration()
        {
            MockType type1 =
                new MockType("Entity1")
                .Property<int>("ID");

            MockType type2 =
                new MockType("Entity2")
                .Property<int>("ID")
                .Property(type1, "Relation");

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.AddEntity(type2).AddNavigationProperty(type2.GetProperty("Relation"), EdmMultiplicity.One);

            IEdmModel model = builder.GetEdmModel();
            IEdmEntityType entity = model.AssertHasEntityType(type2);

            entity.AssertHasNavigationProperty(model, "Relation", type1, isNullable: false, multiplicity: EdmMultiplicity.One);
        }
        public void RequiredAttributeEdmPropertyConvention_DoesnotOverwriteExistingConfigurationForNavigationProperties()
        {
            MockType anotherType =
                new MockType("RelatedEntity")
                .Property<int>("ID");

            MockType type =
                new MockType("Entity")
                .Property(typeof(int), "ID")
                .Property(anotherType, "RelatedEntity", new RequiredAttribute());

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.AddEntityType(type).AddNavigationProperty(type.GetProperty("RelatedEntity"), EdmMultiplicity.ZeroOrOne);

            IEdmModel model = builder.GetEdmModel();
            IEdmEntityType entity = model.AssertHasEntityType(type);
            entity.AssertHasNavigationProperty(model, "RelatedEntity", anotherType, isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne);
        }
        public void Apply_throws_when_cannot_find_navigation_property()
        {
            var mockTypeA = new MockType("A");
            mockTypeA.Property(typeof(int), "BId");
            var mockPropertyInfo = mockTypeA.GetProperty("BId");

            Assert.Equal(
                Strings.ForeignKeyAttributeConvention_InvalidNavigationProperty("BId", mockTypeA.Object, "Missing"),
                Assert.Throws<InvalidOperationException>(
                    () => new ForeignKeyPrimitivePropertyAttributeConvention.ForeignKeyAttributeConventionImpl()
                              .Apply(mockPropertyInfo, new ModelConfiguration(), new ForeignKeyAttribute("Missing"))).Message);
        }
        public void RemoveBaseTypeProperties_RemovesAllBaseTypePropertiesFromDerivedTypes()
        {
            var mockType1 = new MockType("Foo").Property<int>("P1");
            var mockType2 = new MockType("Bar").BaseType(mockType1).Property<int>("P1").Property<int>("P2");
            var mockType3 = new MockType("FooBar").BaseType(mockType2).Property<int>("P1").Property<int>("P2");

            var mockAssembly = new MockAssembly(mockType1, mockType2, mockType3);

            HttpConfiguration configuration = new HttpConfiguration();
            configuration.Services.Replace(typeof(IAssembliesResolver), new TestAssemblyResolver(mockAssembly));
            var builder = new ODataConventionModelBuilder(configuration);

            var entity1 = builder.AddEntity(mockType1);
            entity1.AddProperty(mockType1.GetProperty("P1"));

            var entity2 = builder.AddEntity(mockType2).DerivesFrom(entity1);
            entity2.AddProperty(mockType2.GetProperty("P2"));

            var entity3 = builder.AddEntity(mockType3);
            entity3.AddProperty(mockType3.GetProperty("P1"));
            entity3.AddProperty(mockType3.GetProperty("P2"));

            builder.RemoveBaseTypeProperties(entity3, entity2);

            Assert.Empty(entity3.Properties);
        }
        public void ODataConventionModelBuilder_IgnoresIndexerProperties()
        {
            MockType type =
                new MockType("ComplexType")
                .Property<int>("Item");

            MockPropertyInfo pi = type.GetProperty("Item");
            pi.Setup(p => p.GetIndexParameters()).Returns(new[] { new Mock<ParameterInfo>().Object }); // make it indexer

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.AddComplexType(type);

            IEdmModel model = builder.GetEdmModel();
            IEdmComplexType complexType = model.AssertHasComplexType(type);
            Assert.Empty(complexType.Properties());
        }
        public void ODataConventionModelBuilder_Sets_IsAddedExplicitly_Appropriately()
        {
            // Arrange
            MockType relatedEntity =
                new MockType("RelatedEntity")
                .Property<int>("ID");
            MockType relatedComplexType =
                new MockType("RelatedComplexType");
            MockType type =
                new MockType()
                .Property<int>("ID")
                .Property<int>("ExplicitlyAddedPrimitive")
                .Property<int>("InferredPrimitive")
                .Property<int[]>("ExplicitlyAddedPrimitiveCollection")
                .Property<int[]>("InferredAddedPrimitiveCollection")
                .Property(relatedComplexType, "ExplicitlyAddedComplex")
                .Property(relatedComplexType, "InferredComplex")
                .Property(relatedComplexType.AsCollection(), "ExplicitlyAddedComplexCollection")
                .Property(relatedComplexType.AsCollection(), "InferredComplexCollection")
                .Property(relatedEntity, "ExplicitlyAddedNavigation")
                .Property(relatedEntity, "InferredNavigation")
                .Property(relatedEntity.AsCollection(), "ExplicitlyAddedNavigationCollection")
                .Property(relatedEntity.AsCollection(), "InferredNavigationCollection");

            var builder = new ODataConventionModelBuilder();
            var entity = builder.AddEntity(type);
            entity.AddProperty(type.GetProperty("ExplicitlyAddedPrimitive"));
            entity.AddCollectionProperty(type.GetProperty("ExplicitlyAddedPrimitiveCollection"));
            entity.AddComplexProperty(type.GetProperty("ExplicitlyAddedComplex"));
            entity.AddCollectionProperty(type.GetProperty("ExplicitlyAddedComplexCollection"));
            entity.AddNavigationProperty(type.GetProperty("ExplicitlyAddedNavigation"), EdmMultiplicity.ZeroOrOne);
            entity.AddNavigationProperty(type.GetProperty("ExplicitlyAddedNavigationCollection"), EdmMultiplicity.Many);

            builder.OnModelCreating = (b) =>
                {
                    var explicitlyAddedProperties = entity.Properties.Where(p => p.Name.Contains("ExplicitlyAdded"));
                    var inferredProperties = entity.Properties.Where(p => p.Name.Contains("Inferred"));

                    Assert.Equal(13, entity.Properties.Count());
                    Assert.Equal(6, explicitlyAddedProperties.Count());
                    Assert.Equal(6, inferredProperties.Count());
                    foreach (var explicitlyAddedProperty in explicitlyAddedProperties)
                    {
                        Assert.True(explicitlyAddedProperty.AddedExplicitly);
    }
                    foreach (var inferredProperty in inferredProperties)
                    {
                        Assert.False(inferredProperty.AddedExplicitly);
                    }
                };

            Assert.DoesNotThrow(() => builder.GetEdmModel());
        }
        public void DerivedType_DataMemberRequired_IsHonored_IfDerivedtypeIsDataContract()
        {
            // Arrange
            MockType baseType = new MockType("BaseMocktype");
            baseType.Setup(t => t.GetCustomAttributes(It.IsAny<Type>(), It.IsAny<bool>())).Returns(new[] { new DataContractAttribute() });

            MockType derivedType =
                new MockType("DerivedMockType")
                .Property(typeof(int), "Property", new[] { new DataMemberAttribute { IsRequired = true } })
                .BaseType(baseType);

            PropertyInfo property = derivedType.GetProperty("Property");
            Mock<StructuralTypeConfiguration> structuralType = new Mock<StructuralTypeConfiguration>();
            Mock<StructuralPropertyConfiguration> structuralProperty = new Mock<StructuralPropertyConfiguration>(property, structuralType.Object);
            structuralType.Setup(t => t.ClrType).Returns(derivedType);

            // Act
            new DataMemberAttributeEdmPropertyConvention().Apply(structuralProperty.Object, structuralType.Object);

            // Assert
            Assert.False(structuralProperty.Object.OptionalProperty);
        }