public void Configure_should_configure_inverse()
        {
            var inverseMockPropertyInfo = new MockPropertyInfo();
            var navigationPropertyConfiguration = new NavigationPropertyConfiguration(new MockPropertyInfo())
                                                      {
                                                          InverseNavigationProperty = inverseMockPropertyInfo
                                                      };
            var associationType = new EdmAssociationType().Initialize();
            var inverseAssociationType = new EdmAssociationType().Initialize();
            var model = new EdmModel().Initialize();
            model.AddAssociationType(inverseAssociationType);
            var inverseNavigationProperty
                = model.AddEntityType("T")
                    .AddNavigationProperty("N", inverseAssociationType);
            inverseNavigationProperty.SetClrPropertyInfo(inverseMockPropertyInfo);

            navigationPropertyConfiguration.Configure(
                new EdmNavigationProperty
                    {
                        Association = associationType
                    }, model, new EntityTypeConfiguration(typeof(object)));

            Assert.Same(associationType, inverseNavigationProperty.Association);
            Assert.Same(associationType.SourceEnd, inverseNavigationProperty.ResultEnd);
            Assert.Equal(0, model.GetAssociationTypes().Count());
        }
        public void MapComplexType_should_not_map_invalid_structural_type()
        {
            var model = new EdmModel().Initialize();
            var typeMapper = new TypeMapper(new MappingContext(new ModelConfiguration(), new ConventionsConfiguration(), model));

            Assert.Null(typeMapper.MapComplexType(typeof(string)));
        }
        public void Generate_should_correctly_map_string_primitive_property_facets()
        {
            var model = new EdmModel().Initialize();
            var entityType = model.AddEntityType("E");
            entityType.SetClrType(typeof(object));
            model.AddEntitySet("ESet", entityType);
            var property = entityType.AddPrimitiveProperty("P");
            property.PropertyType.EdmType = EdmPrimitiveType.String;

            property.PropertyType.IsNullable = false;
            property.PropertyType.PrimitiveTypeFacets.IsFixedLength = true;
            property.PropertyType.PrimitiveTypeFacets.IsMaxLength = true;
            property.PropertyType.PrimitiveTypeFacets.IsUnicode = true;
            property.PropertyType.PrimitiveTypeFacets.MaxLength = 42;
            property.PropertyType.PrimitiveTypeFacets.Precision = 23;
            property.PropertyType.PrimitiveTypeFacets.Scale = 77;
            property.SetStoreGeneratedPattern(DbStoreGeneratedPattern.Identity);

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

            var column = databaseMapping.GetEntityTypeMapping(entityType).TypeMappingFragments.Single().PropertyMappings.Single().Column;

            Assert.False(column.IsNullable);
            Assert.Null(column.Facets.IsFixedLength);
            Assert.Equal(true, column.Facets.IsMaxLength);
            Assert.Null(column.Facets.IsUnicode);
            Assert.Equal(42, column.Facets.MaxLength);
            Assert.Null(column.Facets.Precision);
            Assert.Null(column.Facets.Scale);
            Assert.Equal(DbStoreGeneratedPattern.Identity, column.StoreGeneratedPattern);
        }
        public void GetClrTypes_should_return_ospace_types()
        {
            var model = new EdmModel().Initialize();
            model.AddEntityType("A").SetClrType(typeof(object));
            model.AddEntityType("B").SetClrType(typeof(string));

            Assert.Equal(2, model.GetClrTypes().Count());
        }
        public void Can_get_and_set_provider_info_annotation()
        {
            var model = new EdmModel();
            var providerInfo = ProviderRegistry.Sql2008_ProviderInfo;

            model.SetProviderInfo(providerInfo);

            Assert.Same(providerInfo, model.GetProviderInfo());
        }
        public void Apply_should_ignore_current_entity_set()
        {
            var model = new EdmModel().Initialize();
            var entitySet = model.AddEntitySet("Cats", new EdmEntityType());

            ((IEdmConvention<EdmEntitySet>)new PluralizingEntitySetNameConvention())
                .Apply(entitySet, model);

            Assert.Equal("Cats", entitySet.Name);
        }
        public void ApplyModel_should_run_model_conventions()
        {
            var model = new EdmModel().Initialize();
            var mockConvention = new Mock<IEdmConvention>();
            var conventionsConfiguration = new ConventionsConfiguration(new[] { mockConvention.Object });

            conventionsConfiguration.ApplyModel(model);

            mockConvention.Verify(c => c.Apply(model), Times.AtMostOnce());
        }
        public void Generate_should_initialize_mapping_model()
        {
            var model = new EdmModel().Initialize();

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

            Assert.NotNull(databaseMapping);
            Assert.NotNull(databaseMapping.Database);
            Assert.Same(model.Containers.Single(), databaseMapping.EntityContainerMappings.Single().EntityContainer);
        }
        private static DbDatabaseMapping InitializeDatabaseMapping(EdmModel model)
        {
            //Contract.Requires(model != null);

            var databaseMapping = new DbDatabaseMapping().Initialize(
                model, new DbDatabaseMetadata().Initialize(model.Version));

            databaseMapping.EntityContainerMappings.Single().EntityContainer = model.Containers.Single();

            return databaseMapping;
        }
 private static void FixNavigationProperties(
     EdmModel model, EdmAssociationType unifiedAssociation, EdmAssociationType redundantAssociation)
 {
     foreach (var navigationProperty
         in model.GetEntityTypes()
             .SelectMany(e => e.NavigationProperties)
             .Where(np => np.Association == redundantAssociation))
     {
         navigationProperty.Association = unifiedAssociation;
         navigationProperty.ResultEnd = unifiedAssociation.SourceEnd;
     }
 }
        public DbDatabaseMapping Generate(EdmModel model)
        {
            //Contract.Requires(model != null);

            var databaseMapping = InitializeDatabaseMapping(model);

            GenerateEntityTypes(model, databaseMapping);
            GenerateDiscriminators(databaseMapping);
            GenerateAssociationTypes(model, databaseMapping);

            return databaseMapping;
        }
        public void MapComplexType_should_not_map_ignored_type()
        {
            var model = new EdmModel().Initialize();
            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);
        }
        public void HasCascadeDeletePath_should_return_true_for_self_ref_cascade()
        {
            var model = new EdmModel().Initialize();
            var entityType = model.AddEntityType("A");
            var associationType = new EdmAssociationType().Initialize();
            associationType.SourceEnd.EntityType
                = associationType.TargetEnd.EntityType
                  = entityType;
            associationType.SourceEnd.DeleteAction = EdmOperationAction.Cascade;
            model.AddAssociationType(associationType);

            Assert.True(model.HasCascadeDeletePath(entityType, entityType));
        }
        public void Map_should_not_detect_arrays_as_collection_associations()
        {
            var modelConfiguration = new ModelConfiguration();
            var model = new EdmModel().Initialize();
            var entityType = new EdmEntityType();
            var mappingContext = new MappingContext(modelConfiguration, new ConventionsConfiguration(), model);

            new NavigationPropertyMapper(new TypeMapper(mappingContext))
                .Map(new MockPropertyInfo(typeof(NavigationPropertyMapperTests[]), "Nav"), entityType,
                    () => new EntityTypeConfiguration(typeof(object)));

            Assert.Equal(0, model.Namespaces.Single().AssociationTypes.Count);
        }
        public void Apply_is_noop_when_unknown_dependent()
        {
            var model = new EdmModel().Initialize();
            var associationType = new EdmAssociationType().Initialize();
            var navigationProperty = new EdmNavigationProperty { Association = associationType };
            var foreignKeyAnnotation = new ForeignKeyAttribute("AId");
            navigationProperty.Annotations.SetClrAttributes(new[] { foreignKeyAnnotation });

            ((IEdmConvention<EdmNavigationProperty>)new ForeignKeyNavigationPropertyAttributeConvention())
                .Apply(navigationProperty, model);

            Assert.Null(associationType.Constraint);
        }
        public void Configure_should_configure_entity_set_name()
        {
            var model = new EdmModel().Initialize();
            var entityType = new EdmEntityType { Name = "E" };
            var entitySet = model.AddEntitySet("ESet", entityType);

            var entityTypeConfiguration = new EntityTypeConfiguration(typeof(object)) { EntitySetName = "MySet" };

            entityTypeConfiguration.Configure(entityType, model);

            Assert.Equal("MySet", entitySet.Name);
            Assert.Same(entityTypeConfiguration, entitySet.GetConfiguration());
        }
        private void GenerateEntityTypes(EdmModel model, DbDatabaseMapping databaseMapping)
        {
            //Contract.Requires(model != null);
            //Contract.Requires(databaseMapping != null);

            foreach (var entityType in model.GetEntityTypes())
            {
                if (!entityType.IsAbstract)
                {
                    new EntityTypeMappingGenerator(_providerManifest).
                        Generate(entityType, databaseMapping);
                }
            }
        }
        public void MapEntityType_should_not_bring_in_base_class_by_default()
        {
            var model = new EdmModel().Initialize();
            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.Namespaces.Single().EntityTypes.Count);
            Assert.Equal(1, model.Containers.Single().EntitySets.Count);
            Assert.Equal("Bar", model.GetEntitySet(entityType).Name);
        }
        public MappingContext(
            ModelConfiguration modelConfiguration,
            ConventionsConfiguration conventionsConfiguration,
            EdmModel model)
        {
            //Contract.Requires(modelConfiguration != null);
            //Contract.Requires(conventionsConfiguration != null);
            //Contract.Requires(model != null);

            _modelConfiguration = modelConfiguration;
            _conventionsConfiguration = conventionsConfiguration;
            _model = model;
            _attributeProvider = new AttributeProvider();
        }
        public void ApplyModel_should_run_targeted_model_conventions()
        {
            var model = new EdmModel().Initialize();
            var entityType = model.AddEntityType("E");
            var mockConvention = new Mock<IEdmConvention<EdmEntityType>>();
            var conventionsConfiguration = new ConventionsConfiguration(new IConvention[]
                {
                    mockConvention.Object
                });

            conventionsConfiguration.ApplyModel(model);

            mockConvention.Verify(c => c.Apply(entityType, model), Times.AtMostOnce());
        }
        void IEdmConvention.Apply(EdmModel model)
        {
            var associationPairs
                = (from a1 in model.GetAssociationTypes()
                   from a2 in model.GetAssociationTypes()
                   where a1 != a2
                   where a1.SourceEnd.EntityType == a2.TargetEnd.EntityType
                         && a1.TargetEnd.EntityType == a2.SourceEnd.EntityType
                   let a1Configuration = a1.GetConfiguration() as NavigationPropertyConfiguration
                   let a2Configuration = a2.GetConfiguration() as NavigationPropertyConfiguration
                   where (((a1Configuration == null)
                           || ((a1Configuration.InverseEndKind == null)
                               && (a1Configuration.InverseNavigationProperty == null)))
                          && ((a2Configuration == null)
                              || ((a2Configuration.InverseEndKind == null)
                                  && (a2Configuration.InverseNavigationProperty == null))))
                   select new
                       {
                           a1,
                           a2
                       })
                    .Distinct((a, b) => a.a1 == b.a2 && a.a2 == b.a1)
                    .GroupBy(
                        (a, b) => a.a1.SourceEnd.EntityType == b.a2.TargetEnd.EntityType
                                  && a.a1.TargetEnd.EntityType == b.a2.SourceEnd.EntityType)
                    .Where(g => g.Count() == 1)
                    .Select(g => g.Single());

            foreach (var pair in associationPairs)
            {
                var unifiedAssociation = pair.a2.GetConfiguration() != null ? pair.a2 : pair.a1;
                var redundantAssociation = unifiedAssociation == pair.a1 ? pair.a2 : pair.a1;

                unifiedAssociation.SourceEnd.EndKind = redundantAssociation.TargetEnd.EndKind;

                if (redundantAssociation.Constraint != null)
                {
                    unifiedAssociation.Constraint = redundantAssociation.Constraint;
                    unifiedAssociation.Constraint.DependentEnd =
                        unifiedAssociation.Constraint.DependentEnd.EntityType == unifiedAssociation.SourceEnd.EntityType
                            ? unifiedAssociation.SourceEnd
                            : unifiedAssociation.TargetEnd;
                }

                FixNavigationProperties(model, unifiedAssociation, redundantAssociation);

                model.RemoveAssociationType(redundantAssociation);
            }
        }
        private static DbDatabaseMapping CreateSimpleModel(double version)
        {
            var model = new EdmModel().Initialize(version);

            var entityType = model.AddEntityType("E");
            entityType.SetClrType(typeof(object));
            model.AddEntitySet("ESet", entityType);

            var property = entityType.AddPrimitiveProperty("Id");
            property.PropertyType.EdmType = EdmPrimitiveType.Int32;
            property.PropertyType.IsNullable = false;
            entityType.DeclaredKeyProperties.Add(property);

            return new DatabaseMappingGenerator(ProviderRegistry.Sql2008_ProviderManifest).Generate(model);
        }
        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 Apply_should_uniquify_names_multiple()
        {
            var model = new EdmModel().Initialize();
            model.AddEntitySet("Cats1", new EdmEntityType());
            var entitySet1 = model.AddEntitySet("Cat", new EdmEntityType());
            var entitySet2 = model.AddEntitySet("Cat", new EdmEntityType());

            ((IEdmConvention<EdmEntitySet>)new PluralizingEntitySetNameConvention())
                .Apply(entitySet1, model);

            ((IEdmConvention<EdmEntitySet>)new PluralizingEntitySetNameConvention())
                .Apply(entitySet2, model);

            Assert.Equal("Cats", entitySet1.Name);
            Assert.Equal("Cats2", entitySet2.Name);
        }
        public void Map_should_detect_collection_associations_and_set_correct_end_kinds()
        {
            var modelConfiguration = new ModelConfiguration();
            var model = new EdmModel().Initialize();
            var entityType = new EdmEntityType();
            var mappingContext = new MappingContext(modelConfiguration, new ConventionsConfiguration(), model);

            new NavigationPropertyMapper(new TypeMapper(mappingContext))
                .Map(new MockPropertyInfo(typeof(List<NavigationPropertyMapperTests>), "Nav"), entityType,
                    () => new EntityTypeConfiguration(typeof(object)));

            Assert.Equal(1, model.Namespaces.Single().AssociationTypes.Count);

            var associationType = model.Namespaces.Single().AssociationTypes.Single();

            Assert.Equal(EdmAssociationEndKind.Optional, associationType.SourceEnd.EndKind);
            Assert.Equal(EdmAssociationEndKind.Many, associationType.TargetEnd.EndKind);
        }
        public void Apply_generates_constraint_when_simple_fk()
        {
            var model = new EdmModel().Initialize();
            var entityType = model.AddEntityType("E");
            var associationType = model.AddAssociationType("A",
                entityType, EdmAssociationEndKind.Optional,
                entityType, EdmAssociationEndKind.Many);
            var navigationProperty = entityType.AddNavigationProperty("N", associationType);
            var fkProperty = entityType.AddPrimitiveProperty("Fk");
            var foreignKeyAnnotation = new ForeignKeyAttribute("Fk");
            navigationProperty.Annotations.SetClrAttributes(new[] { foreignKeyAnnotation });

            ((IEdmConvention<EdmNavigationProperty>)new ForeignKeyNavigationPropertyAttributeConvention())
                .Apply(navigationProperty, model);

            Assert.NotNull(associationType.Constraint);
            Assert.True(associationType.Constraint.DependentProperties.Contains(fkProperty));
        }
        internal static DbDatabaseMapping Initialize(
            this DbDatabaseMapping databaseMapping, EdmModel model, DbDatabaseMetadata database)
        {
            //Contract.Requires(databaseMapping != null);
            //Contract.Requires(databaseMapping != null);
            //Contract.Requires(database != null);

            databaseMapping.Model = model;
            databaseMapping.Database = database;
            var entityContainerMapping
                = new DbEntityContainerMapping
                    {
                        EntityContainer = model.Containers.Single()
                    };
            databaseMapping.EntityContainerMappings.Add(entityContainerMapping);

            return databaseMapping;
        }
        public void Map_should_create_association_sets_for_associations()
        {
            var modelConfiguration = new ModelConfiguration();
            var model = new EdmModel().Initialize();
            var entityType = new EdmEntityType { Name = "Source" };
            var mappingContext = new MappingContext(modelConfiguration, new ConventionsConfiguration(), model);

            new NavigationPropertyMapper(new TypeMapper(mappingContext))
                .Map(new MockPropertyInfo(new MockType("Target"), "Nav"), entityType,
                    () => new EntityTypeConfiguration(typeof(object)));

            Assert.Equal(1, model.Containers.Single().AssociationSets.Count);

            var associationSet = model.Containers.Single().AssociationSets.Single();

            Assert.NotNull(associationSet);
            Assert.NotNull(associationSet.ElementType);
            Assert.Equal("Source_Nav", associationSet.Name);
        }
        public void Apply_should_not_match_key_that_is_also_an_fk()
        {
            var model = new EdmModel().Initialize();
            var entityType = new EdmEntityType();
            var property = new EdmProperty().AsPrimitive();

            property.PropertyType.EdmType = EdmPrimitiveType.Int64;
            entityType.DeclaredKeyProperties.Add(property);

            var associationType
                = model.AddAssociationType(
                    "A", new EdmEntityType(), EdmAssociationEndKind.Optional,
                    entityType, EdmAssociationEndKind.Many);
            associationType.Constraint = new EdmAssociationConstraint();
            associationType.Constraint.DependentProperties.Add(property);

            ((IEdmConvention<EdmEntityType>)new StoreGeneratedIdentityKeyConvention())
                .Apply(entityType, model);

            Assert.Null(entityType.DeclaredKeyProperties.Single().GetStoreGeneratedPattern());
        }
        public void Configure_should_configure_active_entities_and_complex_types()
        {
            var mockEntityType = new MockType();
            var mockComplexType = new MockType();

            var model = new EdmModel().Initialize();
            var entityType = model.AddEntityType("E");
            entityType.SetClrType(mockEntityType);
            var complexType = model.AddComplexType("C");
            complexType.SetClrType(mockComplexType);

            var modelConfiguration = new ModelConfiguration();
            var mockComplexTypeConfiguration = new Mock<ComplexTypeConfiguration>(mockComplexType.Object);
            var mockEntityTypeConfiguration = new Mock<EntityTypeConfiguration>(mockEntityType.Object);

            modelConfiguration.Add(mockComplexTypeConfiguration.Object);
            modelConfiguration.Add(mockEntityTypeConfiguration.Object);

            modelConfiguration.Configure(model);

            mockComplexTypeConfiguration.Verify(c => c.Configure(complexType));
            mockEntityTypeConfiguration.Verify(c => c.Configure(entityType, model));
        }