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 SetMessage(MockType mockType)
        {
            var expectedMessage = GetExpectedMessage(mockType);
            var exception       = new MockMissingException(mockType, "Class", "Interface", "Member", "Mock");

            Assert.Equal(expectedMessage, exception.Message);
        }
        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);
            }
        }
Пример #4
0
        public void Configure_should_configure_constraint()
        {
            var mockType         = new MockType();
            var mockPropertyInfo = new MockPropertyInfo(typeof(int), "P");
            var navigationPropertyConfiguration = new NavigationPropertyConfiguration(new MockPropertyInfo())
            {
                Constraint =
                    new ForeignKeyConstraintConfiguration(new[] { mockPropertyInfo.Object })
            };
            var associationType = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);

            associationType.SourceEnd = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace));
            associationType.TargetEnd = new AssociationEndMember("T", new EntityType("E", "N", DataSpace.CSpace));

            associationType.SourceEnd.GetEntityType().Annotations.SetClrType(mockType);
            associationType.SourceEnd.RelationshipMultiplicity = RelationshipMultiplicity.Many;
            var property1 = EdmProperty.Primitive("P", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));

            associationType.SourceEnd.GetEntityType().AddMember(property1);
            var property = property1;

            property.SetClrPropertyInfo(mockPropertyInfo);

            navigationPropertyConfiguration.Configure(
                new NavigationProperty("N", TypeUsage.Create(associationType.TargetEnd.GetEntityType()))
            {
                RelationshipType = associationType
            },
                new EdmModel(DataSpace.CSpace), new EntityTypeConfiguration(typeof(object)));

            Assert.NotNull(associationType.Constraint);
            Assert.Same(associationType.SourceEnd, associationType.Constraint.ToRole);
            Assert.Same(associationType.TargetEnd, associationType.Constraint.FromRole);
            Assert.True(associationType.Constraint.ToProperties.Any());
        }
        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.NullableProperty);
        }
Пример #6
0
        public void ConcurrencyCheckAttributeEdmPropertyConvention_DoesnotOverwriteExistingConfiguration()
        {
            // Arrange
            MockType type =
                new MockType("Entity")
                .Property(typeof(int), "ID")
                .Property(typeof(int), "Count", new ConcurrencyCheckAttribute());

            ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create();
            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);
        }
Пример #7
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);
        }
        public void DataMemberAttributeEdmPropertyConvention_PropertyAliased_IfEnabled(string propertyAlias, bool modelAliasing)
        {
            // Arrange
            MockType relatedType =
                new MockType("RelatedEntity")
                .Property <int>("ID");
            MockType type =
                new MockType("Entity")
                .Property(typeof(int), "ID")
                .Property(relatedType, "RelatedEntity", new DataMemberAttribute {
                Name = "AliasRelatedEntity"
            });

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

            // Act
            ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create(b => b.ModelAliasingEnabled = modelAliasing);

            builder.AddEntityType(type);
            IEdmModel model = builder.GetEdmModel();

            // Assert
            IEdmEntityType entity = model.AssertHasEntityType(type);

            entity.AssertHasKey(model, "ID", EdmPrimitiveTypeKind.Int32);
            entity.AssertHasNavigationProperty(
                model,
                propertyAlias,
                relatedType,
                isNullable: true,
                multiplicity: EdmMultiplicity.ZeroOrOne);
        }
Пример #9
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);
        }
Пример #10
0
        public void EntityKeyConvention_DoesnotFigureOutKeyPropertyOnDerivedTypes()
        {
            MockType baseType =
                new MockType("BaseType")
                .Property <uint>("ID");

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

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

            builder.AddEntity(derivedType).DerivesFrom(builder.AddEntity(baseType));

            IEdmModel model = builder.GetEdmModel();

            IEdmEntityType baseEntity = model.AssertHasEntityType(baseType);

            baseEntity.AssertHasKey(model, "ID", EdmPrimitiveTypeKind.Int64);

            IEdmEntityType derivedEntity = model.AssertHasEntityType(derivedType);

            derivedEntity.AssertHasPrimitiveProperty(model, "DerivedTypeID", EdmPrimitiveTypeKind.Int32, isNullable: false);
        }
Пример #11
0
        public void ConcurrencyCheckAttributeEdmPropertyConvention_ConfiguresETagPropertyAsETag()
        {
            // Arrange
            MockType type =
                new MockType("Entity")
                .Property(typeof(int), "ID")
                .Property(typeof(int?), "Count", new ConcurrencyCheckAttribute());

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

            builder.AddEntityType(type);

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

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

            Assert.Equal(EdmConcurrencyMode.Fixed, property.ConcurrencyMode);
        }
        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);
        }
        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);
            }
        }
Пример #14
0
        public void Cloning_the_model_configuration_clones_type_configurations_and_ignored_types()
        {
            var configuration = new ModelConfiguration();

            var entityType1  = new MockType("E1");
            var complexType1 = new MockType("C1");
            var ignoredType1 = new MockType("I1");

            configuration.Add(new EntityTypeConfiguration(entityType1));
            configuration.Add(new ComplexTypeConfiguration(complexType1));
            configuration.Ignore(ignoredType1);
            configuration.DefaultSchema  = "Foo";
            configuration.ModelNamespace = "Bar";

            var clone = configuration.Clone();

            Assert.True(clone.Entities.Contains(entityType1));
            Assert.True(clone.ComplexTypes.Contains(complexType1));
            Assert.True(clone.IsIgnoredType(ignoredType1));
            Assert.Equal("Foo", clone.DefaultSchema);
            Assert.Equal("Bar", clone.ModelNamespace);

            var entityType2  = new MockType("E2");
            var complexType2 = new MockType("C2");
            var ignoredType2 = new MockType("I2");

            configuration.Add(new EntityTypeConfiguration(entityType2));
            configuration.Add(new ComplexTypeConfiguration(complexType2));
            configuration.Ignore(ignoredType2);

            Assert.False(clone.Entities.Contains(entityType2));
            Assert.False(clone.ComplexTypes.Contains(complexType2));
            Assert.False(clone.IsIgnoredType(ignoredType2));
        }
Пример #15
0
        public void Configure_should_configure_delete_action()
        {
            var mockType = new MockType();
            var navigationPropertyConfiguration = new NavigationPropertyConfiguration(new MockPropertyInfo())
            {
                DeleteAction = OperationAction.Cascade,
            };
            var associationType = new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace);

            associationType.SourceEnd = new AssociationEndMember("S", new EntityType("E", "N", DataSpace.CSpace));
            associationType.TargetEnd = new AssociationEndMember("T", new EntityType("E", "N", DataSpace.CSpace));

            associationType.SourceEnd.GetEntityType().Annotations.SetClrType(mockType);
            associationType.SourceEnd.RelationshipMultiplicity = RelationshipMultiplicity.Many; // make this the principal
            associationType.TargetEnd.RelationshipMultiplicity = RelationshipMultiplicity.ZeroOrOne;

            navigationPropertyConfiguration.Configure(
                new NavigationProperty("N", TypeUsage.Create(associationType.TargetEnd.GetEntityType()))
            {
                RelationshipType = associationType
            },
                new EdmModel(DataSpace.CSpace), new EntityTypeConfiguration(typeof(object)));

            Assert.Equal(OperationAction.Cascade, associationType.TargetEnd.DeleteBehavior);
        }
        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"));
        }
        public void Apply_DoesnotSetRequiredProperty()
        {
            // Arrange
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            MockType type =
                new MockType("Mocktype")
                .Property(typeof(string), "Property", new[] { new DataMemberAttribute {
                                                                  IsRequired = false
                                                              } });

            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>();

            structuralType.Setup(s => s.ModelBuilder).Returns(builder);
            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, builder);

            // Assert
            Assert.True(structuralProperty.Object.OptionalProperty);
        }
Пример #18
0
        public void GetLoadedTypes()
        {
            // Arrange
            MockType baseType =
                new MockType("BaseType")
                .Property(typeof(int), "ID");

            MockType derivedType =
                new MockType("DerivedType")
                .Property(typeof(int), "DerivedTypeId")
                .BaseType(baseType);

            MockAssembly assembly = new MockAssembly(baseType, derivedType);
            IWebApiAssembliesResolver resolver   = WebApiAssembliesResolverFactory.Create(assembly);
            IEnumerable <Type>        foundTypes = TypeHelper.GetLoadedTypes(resolver);

            IEnumerable <string> definedNames = assembly.GetTypes().Select(t => t.FullName);
            IEnumerable <string> foundNames   = foundTypes.Select(t => t.FullName);

            foreach (string name in definedNames)
            {
                Assert.Contains(name, foundNames);
            }

            Assert.DoesNotContain(typeof(TypeHelperTest), foundTypes);
        }
        public void DerivedType_DataMemberRequired_IsHonored_IfDerivedtypeIsDataContract()
        {
            // Arrange
            ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create();

            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);

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

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

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

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

            // Assert
            Assert.False(structuralProperty.Object.NullableProperty);
        }
        public void Apply_AliasNotSet_InvalidPropertyAlias(string propertyAlias, bool modelAliasing)
        {
            // Arrange
            ODataConventionModelBuilder modelBuilder = ODataConventionModelBuilderHelper.CreateWithModelAliasing(modelAliasing: 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("Property", structuralProperty.Object.Name);
        }
Пример #21
0
            public void IsValidStructuralType_should_return_false_for_nested_types()
            {
                var mockType = new MockType();

                mockType.SetupGet(t => t.DeclaringType).Returns(typeof(object));

                Assert.False(mockType.Object.IsValidStructuralType());
            }
Пример #22
0
        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");
        }
        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");
        }
Пример #24
0
            public void IsValidStructuralType_should_return_false_for_generic_type_definitions()
            {
                var mockType = new MockType();

                mockType.SetupGet(t => t.IsGenericTypeDefinition).Returns(true);

                Assert.False(mockType.Object.IsValidStructuralType());
            }
        public void ClrType_returns_type()
        {
            var type        = new MockType();
            var innerConfig = new EntityTypeConfiguration(type);
            var config      = new ConventionTypeConfiguration(type, () => innerConfig, new ModelConfiguration());

            Assert.Same(type.Object, config.ClrType);
        }
        public void ClrType_returns_type()
        {
            var type        = new MockType();
            var innerConfig = new EntityTypeConfiguration(type);
            var config      = new LightweightEntityConfiguration(type, () => innerConfig);

            Assert.Same(type.Object, config.ClrType);
        }
Пример #27
0
            public void IsValidStructuralType_should_return_true_for_enums()
            {
                var mockType = new MockType();

                mockType.SetupGet(t => t.IsEnum).Returns(true);

                Assert.True(mockType.Object.IsValidStructuralType());
            }
Пример #28
0
            public void IsValidStructuralType_should_return_false_for_value_types()
            {
                var mockType = new MockType();

                mockType.Protected().Setup <bool>("IsValueTypeImpl").Returns(true);

                Assert.False(mockType.Object.IsValidStructuralType());
            }
Пример #29
0
        public void MigrationIds_should_not_return_migration_when_not_subclass_of_db_migration()
        {
            var mockType     = new MockType("20110816231110_Migration", @namespace: "Migrations");
            var mockAssembly = new MockAssembly(mockType);

            var migrationAssembly = new MigrationAssembly(mockAssembly, mockType.Object.Namespace);

            Assert.False(migrationAssembly.MigrationIds.Any());
        }
Пример #30
0
        public void MigrationIds_should_not_return_migration_when_no_default_ctor()
        {
            var mockType     = new MockType("20110816231110_Migration", hasDefaultCtor: false, @namespace: "Migrations");
            var mockAssembly = new MockAssembly(mockType);

            var migrationAssembly = new MigrationAssembly(mockAssembly, mockType.Object.Namespace);

            Assert.False(migrationAssembly.MigrationIds.Any());
        }
Пример #31
0
        public void MigrationIds_should_not_return_migration_when_name_does_not_match_pattern()
        {
            var mockType     = new MockType("Z0110816231110_Migration", @namespace: "Migrations");
            var mockAssembly = new MockAssembly(mockType);

            var migrationAssembly = new MigrationAssembly(mockAssembly, mockType.Object.Namespace);

            Assert.False(migrationAssembly.MigrationIds.Any());
        }
Пример #32
0
        public void ReturnsUsingFixtureThrowsWhenSetupIsNull()
        {
            // Arrange
            var fixture = new Mock <IFixture>();

            // Act & Assert
            Assert.Throws <ArgumentNullException>(
                () => MockType.ReturnsUsingFixture <string, string>(null, fixture.Object));
        }
        public void Apply_should_inline_type()
        {
            var mockType = new MockType();
            var modelConfiguration = new ModelConfiguration();

            new ComplexTypeAttributeConvention.ComplexTypeAttributeConventionImpl()
                .Apply(mockType, modelConfiguration, new ComplexTypeAttribute());

            Assert.True(modelConfiguration.IsComplexType(mockType));
        }
        public void Apply_should_ignore_type()
        {
            var mockType = new MockType();
            var modelConfiguration = new ModelConfiguration();

            new NotMappedTypeAttributeConvention.NotMappedTypeAttributeConventionImpl()
                .Apply(mockType, modelConfiguration, new NotMappedAttribute());

            Assert.True(modelConfiguration.IsIgnoredType(mockType));
        }
        public void Apply_should_ignore_type()
        {
            var mockType           = new MockType();
            var modelConfiguration = new ModelConfiguration();

            new NotMappedTypeAttributeConvention()
            .Apply(mockType, modelConfiguration, new NotMappedAttribute());

            Assert.True(modelConfiguration.IsIgnoredType(mockType));
        }
        public void MapToStoredProcedures_with_no_args_should_add_configuration()
        {
            var type        = new MockType();
            var innerConfig = new EntityTypeConfiguration(type);
            var config      = new LightweightEntityConfiguration(type, () => innerConfig);

            config.MapToStoredProcedures();

            Assert.True(innerConfig.IsMappedToFunctions);
        }
        public void ToTable_configures_when_unset()
        {
            var type        = new MockType();
            var innerConfig = new EntityTypeConfiguration(type);
            var config      = new LightweightEntityConfiguration(type, () => innerConfig);

            config.ToTable("Table1");

            Assert.Equal("Table1", innerConfig.TableName);
        }
        public void HasEntitySetName_configures_when_unset()
        {
            var type = new MockType();
            var innerConfig = new EntityTypeConfiguration(type);
            var config = new LightweightEntityConfiguration(type, () => innerConfig);

            var result = config.HasEntitySetName("EntitySet1");

            Assert.Equal("EntitySet1", innerConfig.EntitySetName);
            Assert.Same(config, result);
        }
        public void HasEntitySetName_evaluates_preconditions()
        {
            var type = new MockType();
            var innerConfig = new EntityTypeConfiguration(type);
            var config = new LightweightEntityConfiguration(type, () => innerConfig);

            var ex = Assert.Throws<ArgumentException>(
                () => config.HasEntitySetName(null));

            Assert.Equal(Strings.ArgumentIsNullOrWhitespace("entitySetName"), ex.Message);
        }
        public void IsIgnoredProperty_should_return_true_if_property_is_ignored()
        {
            var modelConfiguration = new ModelConfiguration();
            var mockType = new MockType();
            var mockPropertyInfo = new MockPropertyInfo(typeof(string), "S");

            Assert.False(modelConfiguration.IsIgnoredProperty(mockType, mockPropertyInfo));

            modelConfiguration.Entity(mockType).Ignore(mockPropertyInfo);

            Assert.True(modelConfiguration.IsIgnoredProperty(mockType, mockPropertyInfo));
        }
        public void GetConfiguredProperties_should_return_all_configured_properties()
        {
            var modelConfiguration = new ModelConfiguration();
            var mockType = new MockType();
            var mockPropertyInfo = new MockPropertyInfo(typeof(string), "S");

            Assert.False(modelConfiguration.GetConfiguredProperties(mockType).Any());

            modelConfiguration.Entity(mockType).Property(new PropertyPath(mockPropertyInfo));

            Assert.Same(mockPropertyInfo.Object, modelConfiguration.GetConfiguredProperties(mockType).Single());
        }
Пример #42
0
        public void Methods_dont_throw_when_configuration_is_null()
        {
            var type = new MockType();
            type.Property<int>("Property1");

            Methods_dont_throw_when_configuration_is_null_implementation(
                () => new ConventionTypeConfiguration(type, () => new EntityTypeConfiguration(type), new ModelConfiguration()));
            Methods_dont_throw_when_configuration_is_null_implementation(
                () => new ConventionTypeConfiguration(type, () => new ComplexTypeConfiguration(type), new ModelConfiguration()));
            Methods_dont_throw_when_configuration_is_null_implementation(
                () => new ConventionTypeConfiguration(type, new ModelConfiguration()));
        }
        public void MapComplexType_should_not_map_ignored_type()
        {
            var model = new EdmModel(DataSpace.CSpace);
            var mockModelConfiguration = new Mock<ModelConfiguration>();
            var typeMapper = new TypeMapper(new MappingContext(mockModelConfiguration.Object, new ConventionsConfiguration(), model));
            var mockType = new MockType("Foo");
            mockModelConfiguration.Setup(m => m.IsIgnoredType(mockType)).Returns(true);

            var complexType = typeMapper.MapComplexType(mockType);

            Assert.Null(complexType);
        }
Пример #44
0
            public void IsValidStructuralProperty_should_return_true_when_property_read_only_collection()
            {
                var mockProperty = new MockPropertyInfo(typeof(List<string>), "Coll");
                mockProperty.SetupGet(p => p.CanWrite).Returns(false);

                var mockType = new MockType();
                mockType.Setup(m => m.GetProperties(It.IsAny<BindingFlags>())).Returns(new[] { mockProperty.Object });

                mockProperty.SetupGet(p => p.DeclaringType).Returns(mockType.Object);

                Assert.True(mockProperty.Object.IsValidStructuralProperty());
            }
        public void Apply_does_not_invoke_action_when_single_predicate_false()
        {
            var actionInvoked = false;
            var convention = new EntityConvention(
                new Func<Type, bool>[] { t => false },
                c => actionInvoked = true);
            var type = new MockType();
            var configuration = new EntityTypeConfiguration(type);

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

            Assert.False(actionInvoked);
        }
        public void Apply_invokes_action_when_no_predicates()
        {
            var actionInvoked = false;
            var convention = new EntityConvention(
                Enumerable.Empty<Func<Type, bool>>(),
                c => actionInvoked = true);
            var type = new MockType();
            var configuration = new EntityTypeConfiguration(type);

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

            Assert.True(actionInvoked);
        }
            public void Invokes_action_when_single_predicate_true()
            {
                var actionInvoked = false;
                var convention = new TypeConvention(
                    new Func<Type, bool>[] { t => true },
                    c => actionInvoked = true);
                var type = new MockType();
                var configuration = new EntityTypeConfiguration(type);

                convention.Apply(type, () => configuration, new ModelConfiguration());

                Assert.True(actionInvoked);
            }
        public void EntityKeyConvention_FiguresOutTheKeyProperty()
        {
            MockType baseType =
                new MockType("BaseType")
                .Property<uint>("ID");

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.AddEntity(baseType);

            IEdmModel model = builder.GetEdmModel();

            IEdmEntityType entity = model.AssertHasEntityType(baseType);
            entity.AssertHasKey(model, "ID", EdmPrimitiveTypeKind.Int64);
        }
        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 MapEntityType_should_not_bring_in_base_class_by_default()
        {
            var model = new EdmModel(DataSpace.CSpace);
            var typeMapper = new TypeMapper(new MappingContext(new ModelConfiguration(), new ConventionsConfiguration(), model));
            var mockType = new MockType("Bar").BaseType(new MockType("Foo"));

            var entityType = typeMapper.MapEntityType(mockType);

            Assert.NotNull(entityType);
            Assert.Null(entityType.BaseType);
            Assert.Equal(1, model.EntityTypes.Count());
            Assert.Equal(1, model.Containers.Single().EntitySets.Count);
            Assert.Equal("Bar", model.GetEntitySet(entityType).Name);
        }
        public void Ctor_evaluates_preconditions()
        {
            var type = new MockType();

            var ex = Assert.Throws<ArgumentNullException>(
                () => new LightweightEntityConfiguration(null, () => new EntityTypeConfiguration(type)));

            Assert.Equal("type", ex.ParamName);

            ex = Assert.Throws<ArgumentNullException>(
                () => new LightweightEntityConfiguration(type, null));

            Assert.Equal("configuration", ex.ParamName);
        }
        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 Apply_does_not_invoke_action_when_value_null()
        {
            var actionInvoked = false;
            var convention = new EntityConventionWithHaving<object>(
                Enumerable.Empty<Func<Type, bool>>(),
                t => null,
                (c, v) => actionInvoked = true);
            var type = new MockType();
            var configuration = new EntityTypeConfiguration(type);

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

            Assert.False(actionInvoked);
        }
        public void RequiredAttributeEdmPropertyConvention_ConfiguresRequiredPropertyAsRequired()
        {
            MockType type =
                new MockType("Entity")
                .Property(typeof(int), "ID")
                .Property(typeof(int?), "Count", new RequiredAttribute());

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

            IEdmModel model = builder.GetEdmModel();
            IEdmEntityType entity = model.AssertHasEntityType(type);
            entity.AssertHasPrimitiveProperty(model, "Count", EdmPrimitiveTypeKind.Int32, isNullable: false);
        }
        public void EntityKeyConvention_DoesnotFigureOutKeyPropertyIfIgnored()
        {
            MockType baseType =
                new MockType("BaseType")
                .Property(typeof(int), "ID", new NotMappedAttribute());

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.AddEntity(baseType);

            IEdmModel model = builder.GetEdmModel();

            IEdmEntityType baseEntity = model.AssertHasEntityType(baseType);
            Assert.Empty(baseEntity.Properties());
            Assert.Empty(baseEntity.Key());
        }
        public void MapEntityType_should_bring_in_derived_types_from_the_same_assembly()
        {
            var model = new EdmModel().Initialize();
            var typeMapper = new TypeMapper(new MappingContext(new ModelConfiguration(), new ConventionsConfiguration(), model));

            var mockType1 = new MockType("Foo");
            var mockType2 = new MockType("Bar").BaseType(mockType1);

            new MockAssembly(mockType1, mockType2);

            typeMapper.MapEntityType(mockType1);

            Assert.Equal(2, model.Namespaces.Single().EntityTypes.Count);
            Assert.Equal(1, model.Containers.Single().EntitySets.Count);
        }
        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 TestModelBuilder Entity(string name, bool addSet = true)
        {
            _entityType = _model.AddEntityType(name);

            Type type = new MockType(name);

            _entityType.Annotations.SetClrType(type);

            if (addSet)
            {
                _model.AddEntitySet(name + "Set", _entityType);
            }

            return this;
        }
Пример #59
0
        public TestModelBuilder Entity(string name, bool addSet = true)
        {
            _entityType = _model.AddEntityType(name);

            Type type = new MockType(name);

            _entityType.GetMetadataProperties().SetClrType(type);

            if (addSet)
            {
                _model.AddEntitySet(name + "Set", _entityType);
            }

            return this;
        }
        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);
        }