private static bool RemapsInheritedProperties(
            DbDatabaseMapping databaseMapping, StorageEntityTypeMapping entityTypeMapping)
        {
            var inheritedProperties = entityTypeMapping.EntityType.Properties
                                                       .Except(entityTypeMapping.EntityType.DeclaredProperties)
                                                       .Except(entityTypeMapping.EntityType.GetKeyProperties());

            foreach (var property in inheritedProperties)
            {
                var fragment = GetFragmentForPropertyMapping(entityTypeMapping, property);

                if (fragment != null)
                {
                    // find if this inherited property is mapped to another table by a base type
                    var baseType = (EntityType)entityTypeMapping.EntityType.BaseType;
                    while (baseType != null)
                    {
                        if (databaseMapping.GetEntityTypeMappings(baseType)
                                           .Select(baseTypeMapping => GetFragmentForPropertyMapping(baseTypeMapping, property))
                                           .Any(
                                               baseFragment => baseFragment != null
                                                               && baseFragment.Table != fragment.Table))
                        {
                            return true;
                        }
                        baseType = (EntityType)baseType.BaseType;
                    }
                }
            }
            return false;
        }
예제 #2
0
        public void Configure_should_update_table_name_when_base_type_is_null()
        {
            var entityMappingConfiguration
                = new EntityMappingConfiguration
                      {
                          TableName = new DatabaseName("Foo")
                      };

            var entityTypeMapping = new StorageEntityTypeMapping(null);

            entityTypeMapping.AddType(new EntityType("E", "N", DataSpace.CSpace));

            var databaseMapping =
                new DbDatabaseMapping().Initialize(new EdmModel(DataSpace.CSpace), new EdmModel(DataSpace.SSpace));

            var table = databaseMapping.Database.AddTable("foo");
            var entitySet = databaseMapping.Database.GetEntitySet(table);

            entityTypeMapping.AddFragment(new StorageMappingFragment(entitySet, entityTypeMapping, false));
            
            entityMappingConfiguration.Configure(
                databaseMapping, ProviderRegistry.Sql2008_ProviderManifest, entityTypeMapping.EntityType, ref entityTypeMapping, false, 0, 1);

            Assert.Equal("Foo", table.GetTableName().Name);
        }
예제 #3
0
        public void WriteMappingFragment_should_write_store_entity_set_name()
        {
            var fixture = new Fixture();

            var entityType = new EntityType("E", "N", DataSpace.CSpace);
            var entitySet = new EntitySet("ES", "S", null, null, entityType);
            var entityContainer = new EntityContainer("EC", DataSpace.SSpace);

            entityContainer.AddEntitySetBase(entitySet);

            var storageEntitySetMapping
                = new StorageEntitySetMapping(
                    entitySet,
                    new StorageEntityContainerMapping(entityContainer));

            StorageTypeMapping typeMapping = new StorageEntityTypeMapping(storageEntitySetMapping);

            var mappingFragment = new StorageMappingFragment(entitySet, typeMapping, false);

            fixture.Writer.WriteMappingFragmentElement(mappingFragment);

            Assert.Equal(
                @"<MappingFragment StoreEntitySet=""ES"" />",
                fixture.ToString());
        }
            public static string GetIdentity(StorageEntityTypeMapping mapping)
            {
                var types = mapping.Types.Select(it => it.Identity)
                            .OrderBy(it => it, StringComparer.Ordinal);
                var isOfTypes = mapping.IsOfTypes.Select(it => it.Identity)
                                .OrderBy(it => it, StringComparer.Ordinal);

                return(string.Join(",", types.Concat(isOfTypes)));
            }
        public void AddType_throws_for_null_type()
        {
            var entityTypeMapping
                = new StorageEntityTypeMapping(
                    new StorageEntitySetMapping(
                        new EntitySet(), 
                        new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace))));

            Assert.Equal(
                "type",
                Assert.Throws<ArgumentNullException>(() => entityTypeMapping.AddType(null)).ParamName);
        }
        public void Can_get_set_mapping()
        {
            var storageSetMapping
                = new StorageEntitySetMapping(
                    new EntitySet(),
                    new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace)));

            var storageTypeMapping
                = new StorageEntityTypeMapping(storageSetMapping);

            Assert.Same(storageSetMapping, storageTypeMapping.SetMapping);
        }
        public static StorageEntityTypeMapping Clone(this StorageEntityTypeMapping entityTypeMapping)
        {
            DebugCheck.NotNull(entityTypeMapping);

            var clone = new StorageEntityTypeMapping(null);

            clone.AddType(entityTypeMapping.EntityType);

            entityTypeMapping.Annotations.Copy(clone.Annotations);

            return clone;
        }
        public void AddType_throws_for_null_type()
        {
            var entityTypeMapping
                = new StorageEntityTypeMapping(
                      new StorageEntitySetMapping(
                          new EntitySet(),
                          new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace))));

            Assert.Equal(
                "type",
                Assert.Throws <ArgumentNullException>(() => entityTypeMapping.AddType(null)).ParamName);
        }
예제 #9
0
        public static void GetIdentity_of_StorageMappingFragment_returns_expected_value()
        {
            var entityType        = new EntityType("ET", "N", DataSpace.CSpace);
            var entitySet         = new EntitySet("ES", "S", "T", null, entityType);
            var entityTypeMapping = new StorageEntityTypeMapping(null);

            entityTypeMapping.AddType(entityType);
            var mappingFragment = new StorageMappingFragment(entitySet, entityTypeMapping, false);

            Assert.Equal(entitySet.Identity,
                         BaseMetadataMappingVisitor.IdentityHelper.GetIdentity(mappingFragment));
        }
예제 #10
0
        public void Can_get_set_mapping()
        {
            var storageSetMapping
                = new StorageEntitySetMapping(
                      new EntitySet(),
                      new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace)));

            var storageTypeMapping
                = new StorageEntityTypeMapping(storageSetMapping);

            Assert.Same(storageSetMapping, storageTypeMapping.SetMapping);
        }
        public void Can_not_create_mapping_fragment_with_null_entity_set()
        {
            var entityTypeMapping =
                new StorageEntityTypeMapping(
                    new StorageEntitySetMapping(
                        new EntitySet(),
                        new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace))));

            Assert.Equal(
                "tableExtent",
                Assert.Throws <ArgumentNullException>(
                    () => new StorageMappingFragment(null, entityTypeMapping, false)).ParamName);
        }
        public void Can_not_create_mapping_fragment_with_null_entity_set()
        {
            var entityTypeMapping = 
                new StorageEntityTypeMapping(
                new StorageEntitySetMapping(
                    new EntitySet(),
                    new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace))));

            Assert.Equal(
                "tableExtent",
                Assert.Throws<ArgumentNullException>(
                    () => new StorageMappingFragment(null, entityTypeMapping, false)).ParamName);
        }
        public void Can_get_entity_type()
        {
            var entityTypeMapping 
                = new StorageEntityTypeMapping(
                    new StorageEntitySetMapping(new EntitySet(), new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace))));

            Assert.Null(entityTypeMapping.EntityType);

            var entityType = new EntityType("E", "N", DataSpace.CSpace);

            entityTypeMapping.AddType(entityType);

            Assert.Same(entityType, entityTypeMapping.EntityType);
        }
        public void Can_get_entity_type()
        {
            var entityTypeMapping
                = new StorageEntityTypeMapping(
                      new StorageEntitySetMapping(new EntitySet(), new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace))));

            Assert.Null(entityTypeMapping.EntityType);

            var entityType = new EntityType("E", "N", DataSpace.CSpace);

            entityTypeMapping.AddType(entityType);

            Assert.Same(entityType, entityTypeMapping.EntityType);
        }
        public void Can_get_entity_type_mappings()
        {
            var entityContainerMapping = new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace));
            var entitySetMapping = new StorageEntitySetMapping(new EntitySet(), entityContainerMapping);

            Assert.Empty(entitySetMapping.EntityTypeMappings);

            var entityTypeMapping
                = new StorageEntityTypeMapping(
                    new StorageEntitySetMapping(new EntitySet(), entityContainerMapping));

            entitySetMapping.AddTypeMapping(entityTypeMapping);

            Assert.Same(entityTypeMapping, entitySetMapping.EntityTypeMappings.Single());
        }
        public void Can_get_entity_type_mappings()
        {
            var entityContainerMapping = new StorageEntityContainerMapping(new EntityContainer());
            var entitySetMapping       = new StorageEntitySetMapping(new EntitySet(), entityContainerMapping);

            Assert.Empty(entitySetMapping.EntityTypeMappings);

            var entityTypeMapping
                = new StorageEntityTypeMapping(
                      new StorageEntitySetMapping(new EntitySet(), entityContainerMapping));

            entitySetMapping.AddTypeMapping(entityTypeMapping);

            Assert.Same(entityTypeMapping, entitySetMapping.EntityTypeMappings.Single());
        }
예제 #17
0
        public static void GetIdentity_of_StorageEntityTypeMapping_returns_expected_value()
        {
            var entityType1 = new EntityType("ET1", "N", DataSpace.CSpace);
            var entityType2 = new EntityType("ET2", "N", DataSpace.CSpace);
            var entityType3 = new EntityType("ET3", "N", DataSpace.CSpace);
            var entityType4 = new EntityType("ET4", "N", DataSpace.CSpace);
            var mapping     = new StorageEntityTypeMapping(null);

            mapping.AddType(entityType2);
            mapping.AddType(entityType1);
            mapping.AddIsOfType(entityType4);
            mapping.AddIsOfType(entityType3);

            Assert.Equal("N.ET1,N.ET2,N.ET3,N.ET4",
                         BaseMetadataMappingVisitor.IdentityHelper.GetIdentity((StorageTypeMapping)mapping));
        }
        public void Added_isOfType_returned_in_isOfType_collection()
        {
            var entityTypeMapping
                = new StorageEntityTypeMapping(
                      new StorageEntitySetMapping(
                          new EntitySet(),
                          new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace))));

            Assert.Empty(entityTypeMapping.Types);
            Assert.Empty(entityTypeMapping.IsOfTypes);

            var entityType = new EntityType("E", "N", DataSpace.CSpace);

            entityTypeMapping.AddIsOfType(entityType);

            Assert.Same(entityType, entityTypeMapping.IsOfTypes.Single());
            Assert.Empty(entityTypeMapping.Types);
        }
        public void Added_type_returned_in_type_collection()
        {
            var entityTypeMapping
                = new StorageEntityTypeMapping(
                    new StorageEntitySetMapping(
                        new EntitySet(),
                        new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace))));

            Assert.Empty(entityTypeMapping.Types);
            Assert.Empty(entityTypeMapping.IsOfTypes);

            var entityType = new EntityType("E", "N", DataSpace.CSpace);
            
            entityTypeMapping.AddType(entityType);

            Assert.Same(entityType, entityTypeMapping.Types.Single());
            Assert.Empty(entityTypeMapping.IsOfTypes);
        }
예제 #20
0
        public void Can_add_remove_type_mapping()
        {
            var storageSetMapping
                = new StorageEntitySetMapping(
                      new EntitySet(),
                      new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace)));

            Assert.Empty(storageSetMapping.TypeMappings);

            var entityTypeMapping = new StorageEntityTypeMapping(storageSetMapping);

            storageSetMapping.AddTypeMapping(entityTypeMapping);

            Assert.Same(entityTypeMapping, storageSetMapping.TypeMappings.Single());

            storageSetMapping.RemoveTypeMapping(entityTypeMapping);

            Assert.Empty(storageSetMapping.TypeMappings);
        }
        public void Can_create_hierarchy_mappings()
        {
            var entityTypeMapping
                = new StorageEntityTypeMapping(
                    new StorageEntitySetMapping(new EntitySet(), new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace))));

            Assert.False(entityTypeMapping.IsHierarchyMapping);

            var entityType = new EntityType("E", "N", DataSpace.CSpace);

            entityTypeMapping.AddType(entityType);
            entityTypeMapping.AddIsOfType(entityType);

            Assert.True(entityTypeMapping.IsHierarchyMapping);

            entityTypeMapping.RemoveIsOfType(entityType);

            Assert.False(entityTypeMapping.IsHierarchyMapping);
        }
예제 #22
0
        public void Can_add_remove_type_mapping()
        {
            var storageSetMapping 
                = new StorageEntitySetMapping(
                    new EntitySet(), 
                    new StorageEntityContainerMapping(new EntityContainer()));

            Assert.Empty(storageSetMapping.TypeMappings);

            var entityTypeMapping = new StorageEntityTypeMapping(storageSetMapping);

            storageSetMapping.AddTypeMapping(entityTypeMapping);

            Assert.Same(entityTypeMapping, storageSetMapping.TypeMappings.Single());

            storageSetMapping.RemoveTypeMapping(entityTypeMapping);

            Assert.Empty(storageSetMapping.TypeMappings);
        } 
        public void Can_create_hierarchy_mappings()
        {
            var entityTypeMapping
                = new StorageEntityTypeMapping(
                      new StorageEntitySetMapping(new EntitySet(), new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace))));

            Assert.False(entityTypeMapping.IsHierarchyMapping);

            var entityType = new EntityType("E", "N", DataSpace.CSpace);

            entityTypeMapping.AddType(entityType);
            entityTypeMapping.AddIsOfType(entityType);

            Assert.True(entityTypeMapping.IsHierarchyMapping);

            entityTypeMapping.RemoveIsOfType(entityType);

            Assert.False(entityTypeMapping.IsHierarchyMapping);
        }
예제 #24
0
        public void GetComplexPropertyMappings_should_return_all_complex_property_mappings_for_type()
        {
            var databaseMapping = new DbDatabaseMapping()
                .Initialize(new EdmModel(DataSpace.CSpace), new EdmModel(DataSpace.SSpace));
            var entitySet = new EntitySet
                                {
                                    Name = "ES"
                                };
            var entitySetMapping = databaseMapping.AddEntitySetMapping(entitySet);
            var entityTypeMapping = new StorageEntityTypeMapping(null);
            entitySetMapping.AddTypeMapping(entityTypeMapping);
            var entityTypeMappingFragment = new StorageMappingFragment(entitySet, entityTypeMapping, false);
            entityTypeMapping.AddFragment(entityTypeMappingFragment);
            var complexType = new ComplexType("C");
            var propertyMapping1
                = new ColumnMappingBuilder(
                    new EdmProperty("C"),
                    new[]
                        {
                            EdmProperty.Complex("P1", complexType),
                            EdmProperty.Primitive("P", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String))
                        });
            var type = typeof(object);

            complexType.Annotations.SetClrType(type);

            entityTypeMappingFragment.AddColumnMapping(propertyMapping1);

            var propertyMapping2
                = new ColumnMappingBuilder(
                    new EdmProperty("C"),
                    new List<EdmProperty>
                        {
                            EdmProperty.Complex("P3", complexType),
                            EdmProperty.Primitive(
                                "P2", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String)),
                        });
            entityTypeMappingFragment.AddColumnMapping(propertyMapping2);

            Assert.Equal(2, databaseMapping.GetComplexPropertyMappings(typeof(object)).Count());
        }
예제 #25
0
        public void Can_add_remove_mapping_fragment()
        {
            var storageSetMapping
                = new StorageEntitySetMapping(
                      new EntitySet(),
                      new StorageEntityContainerMapping(new EntityContainer()));

            var storageTypeMapping
                = new StorageEntityTypeMapping(storageSetMapping);

            Assert.Empty(storageTypeMapping.MappingFragments);

            var mappingFragment = new StorageMappingFragment(new EntitySet(), storageTypeMapping, false);

            storageTypeMapping.AddFragment(mappingFragment);

            Assert.Same(mappingFragment, storageTypeMapping.MappingFragments.Single());

            storageTypeMapping.RemoveFragment(mappingFragment);

            Assert.Empty(storageTypeMapping.MappingFragments);
        }
예제 #26
0
        public void Can_add_remove_mapping_fragment()
        {
            var storageSetMapping
                = new StorageEntitySetMapping(
                    new EntitySet(),
                    new StorageEntityContainerMapping(new EntityContainer()));

            var storageTypeMapping
                = new StorageEntityTypeMapping(storageSetMapping);

            Assert.Empty(storageTypeMapping.MappingFragments);

            var mappingFragment = new StorageMappingFragment(new EntitySet(), storageTypeMapping, false);

            storageTypeMapping.AddFragment(mappingFragment);

            Assert.Same(mappingFragment, storageTypeMapping.MappingFragments.Single());

            storageTypeMapping.RemoveFragment(mappingFragment);

            Assert.Empty(storageTypeMapping.MappingFragments);
        }
        public void GetPropertyMapping_should_return_mapping_with_path()
        {
            var entityTypeMapping = new StorageEntityTypeMapping(null);
            var propertyFoo = EdmProperty.Complex("Foo", new ComplexType());
            var propertyBar = EdmProperty.Primitive("Bar", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));

            var entityPropertyMapping
                = new ColumnMappingBuilder(
                    EdmProperty.Primitive("C", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String)),
                    new[]
                        {
                            propertyFoo,
                            propertyBar,
                        });

            var entityTypeMappingFragment
                = new StorageMappingFragment(new EntitySet(), entityTypeMapping, false);

            entityTypeMappingFragment.AddColumnMapping(entityPropertyMapping);
            entityTypeMapping.AddFragment(entityTypeMappingFragment);

            Assert.Same(entityPropertyMapping, entityTypeMapping.GetPropertyMapping(propertyFoo, propertyBar));
        }
        public void Generate(EntityType entityType, DbDatabaseMapping databaseMapping)
        {
            DebugCheck.NotNull(entityType);
            DebugCheck.NotNull(databaseMapping);

            var entitySet = databaseMapping.Model.GetEntitySet(entityType);

            var entitySetMapping
                = databaseMapping.GetEntitySetMapping(entitySet)
                  ?? databaseMapping.AddEntitySetMapping(entitySet);

            var table
                = entitySetMapping.EntityTypeMappings.Any()
                      ? entitySetMapping.EntityTypeMappings.First().MappingFragments.First().Table
                      : databaseMapping.Database.AddTable(entityType.GetRootType().Name);

            var entityTypeMapping = new StorageEntityTypeMapping(null);

            var entityTypeMappingFragment
                = new StorageMappingFragment(databaseMapping.Database.GetEntitySet(table), entityTypeMapping, false);

            entityTypeMapping.AddType(entityType);
            entityTypeMapping.AddFragment(entityTypeMappingFragment);
            entityTypeMapping.SetClrType(entityType.GetClrType());

            entitySetMapping.AddTypeMapping(entityTypeMapping);

            new PropertyMappingGenerator(_providerManifest)
                .Generate(
                    entityType,
                    entityType.Properties,
                    entitySetMapping,
                    entityTypeMappingFragment,
                    new List<EdmProperty>(),
                    false);
        }
        internal void ConfigureTablesAndConditions(
            StorageEntityTypeMapping entityTypeMapping,
            DbDatabaseMapping databaseMapping,
            DbProviderManifest providerManifest)
        {
            DebugCheck.NotNull(databaseMapping);
            DebugCheck.NotNull(providerManifest);

            var entityType
                = (entityTypeMapping != null)
                      ? entityTypeMapping.EntityType
                      : databaseMapping.Model.GetEntityType(ClrType);

            if (_entityMappingConfigurations.Any())
            {
                for (var i = 0; i < _entityMappingConfigurations.Count; i++)
                {
                    _entityMappingConfigurations[i]
                        .Configure(
                            databaseMapping,
                            providerManifest,
                            entityType,
                            ref entityTypeMapping,
                            IsMappingAnyInheritedProperty(entityType),
                            i,
                            _entityMappingConfigurations.Count);
                }
            }
            else
            {
                ConfigureUnconfiguredType(databaseMapping, providerManifest, entityType);
            }
        }
        private void RemoveFragment(
            EntitySet entitySet, StorageEntityTypeMapping entityTypeMapping, StorageMappingFragment fragment)
        {
            // Make the default discriminator nullable if this type isn't using it but there is a base type
            var defaultDiscriminator = fragment.GetDefaultDiscriminator();
            if (defaultDiscriminator != null
                && entityTypeMapping.EntityType.BaseType != null)
            {
                var columnMapping =
                    _tableMappings[fragment.Table].ColumnMappings.SingleOrDefault(
                        cm => cm.Column == defaultDiscriminator);
                if (columnMapping != null)
                {
                    var propertyMapping = columnMapping.PropertyMappings.SingleOrDefault(
                        pm => pm.EntityType == entityTypeMapping.EntityType);
                    if (propertyMapping != null)
                    {
                        columnMapping.PropertyMappings.Remove(propertyMapping);
                    }
                }
                defaultDiscriminator.Nullable = true;
            }

            entityTypeMapping.RemoveFragment(fragment);

            if (!entityTypeMapping.MappingFragments.Any())
            {
                _databaseMapping.GetEntitySetMapping(entitySet).RemoveTypeMapping(entityTypeMapping);
            }
        }
        public static void GetIdentity_of_StorageEntityTypeMapping_returns_expected_value()
        {
            var entityType1 = new EntityType("ET1", "N", DataSpace.CSpace);
            var entityType2 = new EntityType("ET2", "N", DataSpace.CSpace);
            var entityType3 = new EntityType("ET3", "N", DataSpace.CSpace);
            var entityType4 = new EntityType("ET4", "N", DataSpace.CSpace);
            var mapping = new StorageEntityTypeMapping(null);
            mapping.AddType(entityType2);
            mapping.AddType(entityType1);
            mapping.AddIsOfType(entityType4);
            mapping.AddIsOfType(entityType3);

            Assert.Equal("N.ET1,N.ET2,N.ET3,N.ET4",
                BaseMetadataMappingVisitor.IdentityHelper.GetIdentity((StorageTypeMapping)mapping));
        }
예제 #32
0
        public void GetEntityTypeMapping_should_return_mapping_for_type_by_clrType()
        {
            var databaseMapping = new DbDatabaseMapping()
                .Initialize(new EdmModel(DataSpace.CSpace), new EdmModel(DataSpace.SSpace));
            var entityType = new EntityType("Foo", "N", DataSpace.CSpace);
            var type = typeof(object);

            entityType.Annotations.SetClrType(type);
            var entityTypeMapping = new StorageEntityTypeMapping(null);
            entityTypeMapping.AddType(entityType);
            entityTypeMapping.SetClrType(typeof(object));
            databaseMapping.AddEntitySetMapping(
                new EntitySet
                    {
                        Name = "ES"
                    }).AddTypeMapping(entityTypeMapping);

            Assert.Same(entityTypeMapping, databaseMapping.GetEntityTypeMapping(typeof(object)));
        }
        public static void GetIdentity_of_StorageMappingFragment_returns_expected_value()
        {
            var entityType = new EntityType("ET", "N", DataSpace.CSpace);
            var entitySet = new EntitySet("ES", "S", "T", null, entityType);
            var entityTypeMapping = new StorageEntityTypeMapping(null);
            entityTypeMapping.AddType(entityType);
            var mappingFragment = new StorageMappingFragment(entitySet, entityTypeMapping, false);

            Assert.Equal(entitySet.Identity,
                BaseMetadataMappingVisitor.IdentityHelper.GetIdentity(mappingFragment));
        }
 private static StorageMappingFragment GetFragmentForPropertyMapping(
     StorageEntityTypeMapping entityTypeMapping, EdmProperty property)
 {
     return entityTypeMapping.MappingFragments
                             .SingleOrDefault(tmf => tmf.ColumnMappings.Any(pm => pm.PropertyPath.Last() == property));
 }
        public static StorageMappingFragment CreateTypeMappingFragment(
            StorageEntityTypeMapping entityTypeMapping, StorageMappingFragment templateFragment, EntitySet tableSet)
        {
            var fragment = new StorageMappingFragment(tableSet, entityTypeMapping, false);

            entityTypeMapping.AddFragment(fragment);

            // Move all PK mappings to the extra fragment
            foreach (
                var pkPropertyMapping in templateFragment.ColumnMappings.Where(pm => pm.ColumnProperty.IsPrimaryKeyColumn))
            {
                CopyPropertyMappingToFragment(pkPropertyMapping, fragment, true);
            }
            return fragment;
        }
예제 #36
0
        public void GetEntityTypeMapping_should_return_mapping_for_type()
        {
            var databaseMapping = new DbDatabaseMapping()
                .Initialize(new EdmModel(DataSpace.CSpace), new EdmModel(DataSpace.SSpace));
            var entityType = new EntityType("E", "N", DataSpace.CSpace);
            var entityTypeMapping = new StorageEntityTypeMapping(null);
            entityTypeMapping.AddType(entityType);
            databaseMapping.AddEntitySetMapping(
                new EntitySet
                    {
                        Name = "ES"
                    }).AddTypeMapping(entityTypeMapping);

            Assert.Same(entityTypeMapping, databaseMapping.GetEntityTypeMapping(entityType));
        }
        public void Generate_should_exclude_sgp_properties_from_corresponding_function_mappings()
        {
            var functionMappingGenerator
                = new ModificationFunctionMappingGenerator(ProviderRegistry.Sql2008_ProviderManifest);

            var databaseMapping
                = new DbDatabaseMapping()
                    .Initialize(new EdmModel(DataSpace.CSpace), new EdmModel(DataSpace.SSpace));

            var entityType = new EntityType("E", "N", DataSpace.CSpace);

            var intProperty = EdmProperty.Primitive("Id", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32));
            intProperty.SetStoreGeneratedPattern(StoreGeneratedPattern.Identity);
            entityType.AddKeyMember(intProperty);

            var stringProperty = EdmProperty.Primitive("Name", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));
            stringProperty.SetStoreGeneratedPattern(StoreGeneratedPattern.Computed);
            entityType.AddMember(stringProperty);

            var entitySetMapping
                = databaseMapping.AddEntitySetMapping(
                    databaseMapping.Model.AddEntitySet("ES", entityType));

            var storageEntityTypeMapping
                = new StorageEntityTypeMapping(
                    new StorageEntitySetMapping(new EntitySet(), databaseMapping.EntityContainerMappings.Single()));

            storageEntityTypeMapping.AddType(entityType);

            var storageMappingFragment = new StorageMappingFragment(new EntitySet(), storageEntityTypeMapping, false);

            storageMappingFragment.AddColumnMapping(
                new ColumnMappingBuilder(new EdmProperty("C0"), new[] { intProperty }));

            storageMappingFragment.AddColumnMapping(
                new ColumnMappingBuilder(new EdmProperty("C1"), new[] { stringProperty }));

            storageEntityTypeMapping.AddFragment(storageMappingFragment);

            entitySetMapping.AddTypeMapping(storageEntityTypeMapping);

            functionMappingGenerator.Generate(entityType, databaseMapping);

            var modificationFunctionMapping
                = entitySetMapping.ModificationFunctionMappings.Single();

            Assert.NotNull(modificationFunctionMapping);

            var functionMapping = modificationFunctionMapping.InsertFunctionMapping;

            Assert.NotNull(functionMapping);
            Assert.Equal(0, functionMapping.ParameterBindings.Count);
            Assert.Equal(2, functionMapping.ResultBindings.Count);

            var function = functionMapping.Function;

            Assert.NotNull(function);
            Assert.Equal("E_Insert", function.Name);
            Assert.Equal(0, function.Parameters.Count);

            functionMapping = modificationFunctionMapping.UpdateFunctionMapping;

            Assert.NotNull(functionMapping);
            Assert.Equal(1, functionMapping.ParameterBindings.Count);
            Assert.Equal(1, functionMapping.ResultBindings.Count);

            function = functionMapping.Function;

            Assert.NotNull(function);
            Assert.Equal("E_Update", function.Name);
            Assert.Equal(1, function.Parameters.Count);

            functionMapping = modificationFunctionMapping.DeleteFunctionMapping;

            Assert.NotNull(functionMapping);
            Assert.Equal(1, functionMapping.ParameterBindings.Count);
            Assert.Null(functionMapping.ResultBindings);

            function = modificationFunctionMapping.DeleteFunctionMapping.Function;

            Assert.NotNull(function);
            Assert.Equal("E_Delete", function.Name);
            Assert.Equal(1, function.Parameters.Count);
        }
        /// <summary>
        ///     Finds interesting entity properties - primary keys (if requested), properties (including complex properties and nested properties)
        ///     with concurrency mode set to fixed and C-Side condition members and adds them to the <paramref
        ///      name="interestingMembers" />.
        /// </summary>
        /// <param name="entityTypeMapping"> Entity type mapping. Must not be null. </param>
        /// <param name="interestingMembersKind"> Scenario the members should be returned for. </param>
        /// <param name="interestingMembers"> The list the interesting members (if any) will be added to. Must not be null. </param>
        private static void FindInterestingEntityMappingMembers(
            StorageEntityTypeMapping entityTypeMapping, InterestingMembersKind interestingMembersKind, List<EdmMember> interestingMembers)
        {
            Debug.Assert(entityTypeMapping != null, "entityTypeMapping != null");
            Debug.Assert(interestingMembers != null, "interestingMembers != null");

            foreach (var propertyMapping in entityTypeMapping.MappingFragments.SelectMany(mf => mf.AllProperties))
            {
                var scalarPropMapping = propertyMapping as StorageScalarPropertyMapping;
                var complexPropMapping = propertyMapping as StorageComplexPropertyMapping;
                var conditionMapping = propertyMapping as StorageConditionPropertyMapping;

                Debug.Assert(!(propertyMapping is StorageEndPropertyMapping), "association mapping properties should be handled elsewhere.");

                Debug.Assert(
                    scalarPropMapping != null ||
                    complexPropMapping != null ||
                    conditionMapping != null, "Unimplemented property mapping");

                //scalar property
                if (scalarPropMapping != null
                    && scalarPropMapping.EdmProperty != null)
                {
                    // (0) if a member is part of the key it is interesting
                    if (MetadataHelper.IsPartOfEntityTypeKey(scalarPropMapping.EdmProperty))
                    {
                        // For backwards compatibility we do return primary keys from the obsolete MetadataWorkspace.GetRequiredOriginalValueMembers() method
                        if (interestingMembersKind == InterestingMembersKind.RequiredOriginalValueMembers)
                        {
                            interestingMembers.Add(scalarPropMapping.EdmProperty);
                        }
                    }
                        //(3) if a scalar property has Fixed concurrency mode then it is "interesting"
                    else if (MetadataHelper.GetConcurrencyMode(scalarPropMapping.EdmProperty)
                             == ConcurrencyMode.Fixed)
                    {
                        interestingMembers.Add(scalarPropMapping.EdmProperty);
                    }
                }
                else if (complexPropMapping != null)
                {
                    // (7) All complex members - partial update scenarios only
                    // (3.1) The complex property or its one of its children has fixed concurrency mode
                    if (interestingMembersKind == InterestingMembersKind.PartialUpdate ||
                        MetadataHelper.GetConcurrencyMode(complexPropMapping.EdmProperty) == ConcurrencyMode.Fixed
                        || HasFixedConcurrencyModeInAnyChildProperty(complexPropMapping))
                    {
                        interestingMembers.Add(complexPropMapping.EdmProperty);
                    }
                }
                else if (conditionMapping != null)
                {
                    //(1) C-Side condition members are 'interesting'
                    if (conditionMapping.EdmProperty != null)
                    {
                        interestingMembers.Add(conditionMapping.EdmProperty);
                    }
                }
            }
        }
        private void WriteEntityTypeMappingElement(StorageEntityTypeMapping entityTypeMapping)
        {
            DebugCheck.NotNull(entityTypeMapping);

            _xmlWriter.WriteStartElement(StorageMslConstructs.EntityTypeMappingElement);
            _xmlWriter.WriteAttributeString(
                StorageMslConstructs.EntityTypeMappingTypeNameAttribute,
                GetEntityTypeName(
                    _entityTypeNamespace + "." + entityTypeMapping.EntityType.Name, entityTypeMapping.IsHierarchyMapping));

            foreach (var mappingFragment in entityTypeMapping.MappingFragments)
            {
                WriteMappingFragmentElement(mappingFragment);
            }

            _xmlWriter.WriteEndElement();
        }
        public void Configure(
            DbDatabaseMapping databaseMapping,
            DbProviderManifest providerManifest,
            EntityType entityType,
            ref StorageEntityTypeMapping entityTypeMapping,
            bool isMappingAnyInheritedProperty,
            int configurationIndex,
            int configurationCount)
        {
            DebugCheck.NotNull(entityType);
            DebugCheck.NotNull(databaseMapping);
            DebugCheck.NotNull(providerManifest);

            var isIdentityTable = entityType.BaseType == null && configurationIndex == 0;

            var fragment = FindOrCreateTypeMappingFragment(
                databaseMapping, ref entityTypeMapping, configurationIndex, entityType, providerManifest);
            var fromTable = fragment.Table;
            bool isTableSharing;
            var toTable = FindOrCreateTargetTable(
                databaseMapping, fragment, entityType, fromTable, out isTableSharing);

            var isSharingTableWithBase = DiscoverIsSharingWithBase(databaseMapping, entityType, toTable);

            // Ensure all specified properties are the only ones present in this fragment and table
            var mappingsToContain = DiscoverAllMappingsToContain(
                databaseMapping, entityType, toTable, isSharingTableWithBase);

            // Validate that specified properties can be mapped
            var mappingsToMove = fragment.ColumnMappings.ToList();

            foreach (var propertyPath in mappingsToContain)
            {
                var propertyMapping = fragment.ColumnMappings.SingleOrDefault(
                    pm =>
                    pm.PropertyPath.SequenceEqual(propertyPath));

                if (propertyMapping == null)
                {
                    throw Error.EntityMappingConfiguration_DuplicateMappedProperty(
                        entityType.Name, propertyPath.ToString());
                }
                mappingsToMove.Remove(propertyMapping);
            }

            // Add table constraint if there are no inherited properties
            if (!isIdentityTable)
            {
                bool isSplitting;
                var parentTable = FindParentTable(
                    databaseMapping,
                    fromTable,
                    entityTypeMapping,
                    toTable,
                    isMappingAnyInheritedProperty,
                    configurationIndex,
                    configurationCount,
                    out isSplitting);
                if (parentTable != null)
                {
                    DatabaseOperations.AddTypeConstraint(databaseMapping.Database, entityType, parentTable, toTable, isSplitting);
                }
            }

            // Update AssociationSetMappings (IAs) and FKs
            if (fromTable != toTable)
            {
                if (Properties == null)
                {
                    AssociationMappingOperations.MoveAllDeclaredAssociationSetMappings(
                        databaseMapping, entityType, fromTable, toTable, !isTableSharing);
                    ForeignKeyPrimitiveOperations.MoveAllDeclaredForeignKeyConstraintsForPrimaryKeyColumns(
                        entityType, fromTable, toTable);
                }
                if (isMappingAnyInheritedProperty)
                {
                    // With TPC, we need to move down FK constraints, even on PKs (except type mapping constraints that are not about associations)
                    ForeignKeyPrimitiveOperations.CopyAllForeignKeyConstraintsForPrimaryKeyColumns(
                        databaseMapping.Database, fromTable, toTable);
                }
            }

            if (mappingsToMove.Any())
            {
                EntityType extraTable = null;
                if (configurationIndex < configurationCount - 1)
                {
                    // Move all extra properties to a single new fragment
                    var anyPropertyMapping = mappingsToMove.First();

                    extraTable
                        = FindTableForTemporaryExtraPropertyMapping(
                            databaseMapping, entityType, fromTable, toTable, anyPropertyMapping);

                    var extraFragment
                        = EntityMappingOperations
                            .CreateTypeMappingFragment(
                                entityTypeMapping, fragment, databaseMapping.Database.GetEntitySet(extraTable));

                    var requiresUpdate = extraTable != fromTable;

                    foreach (var pm in mappingsToMove)
                    {
                        // move the property mapping from toFragment to extraFragment
                        EntityMappingOperations.MovePropertyMapping(
                            databaseMapping.Database, fragment, extraFragment, pm, requiresUpdate, true);
                    }
                }
                else
                {
                    // Move each extra property mapping to a fragment refering to the table with the base mapping
                    EntityType unmappedTable = null;
                    foreach (var pm in mappingsToMove)
                    {
                        extraTable = FindTableForExtraPropertyMapping(
                            databaseMapping, entityType, fromTable, toTable, ref unmappedTable, pm);

                        var extraFragment =
                            entityTypeMapping.MappingFragments.SingleOrDefault(tmf => tmf.Table == extraTable);

                        if (extraFragment == null)
                        {
                            extraFragment
                                = EntityMappingOperations
                                    .CreateTypeMappingFragment(
                                        entityTypeMapping, fragment, databaseMapping.Database.GetEntitySet(extraTable));

                            extraFragment.SetIsUnmappedPropertiesFragment(true);
                        }

                        if (extraTable == fromTable)
                        {
                            // move the default discriminator along with the properties
                            MoveDefaultDiscriminator(fragment, extraFragment);
                        }

                        var requiresUpdate = extraTable != fromTable;
                        EntityMappingOperations.MovePropertyMapping(
                            databaseMapping.Database, fragment, extraFragment, pm, requiresUpdate, true);
                    }
                }
            }

            // Ensure all property mappings refer to the table in the fragment
            // Uniquify: true if table sharing, false otherwise
            //           FK names should be uniquified
            //           declared properties are moved, inherited ones are copied (duplicated)
            EntityMappingOperations.UpdatePropertyMappings(
                databaseMapping.Database, fromTable, fragment, !isTableSharing);

            // Configure Conditions for the fragment
            ConfigureDefaultDiscriminator(entityType, fragment, isSharingTableWithBase);
            ConfigureConditions(databaseMapping, entityType, fragment, providerManifest);

            // Ensure all conditions refer to columns on the table in the fragment
            EntityMappingOperations.UpdateConditions(databaseMapping.Database, fromTable, fragment);

            ForeignKeyPrimitiveOperations.UpdatePrincipalTables(
                databaseMapping, entityType, fromTable, toTable, isMappingAnyInheritedProperty);

            CleanupUnmappedArtifacts(databaseMapping, fromTable);
            CleanupUnmappedArtifacts(databaseMapping, toTable);

            toTable.SetConfiguration(this);
        }
        private StorageMappingFragment FindOrCreateTypeMappingFragment(
            DbDatabaseMapping databaseMapping,
            ref StorageEntityTypeMapping entityTypeMapping,
            int configurationIndex,
            EntityType entityType,
            DbProviderManifest providerManifest)
        {
            StorageMappingFragment fragment = null;

            if (entityTypeMapping == null)
            {
                Debug.Assert(entityType.Abstract);
                new TableMappingGenerator(providerManifest).
                    Generate(entityType, databaseMapping);
                entityTypeMapping = databaseMapping.GetEntityTypeMapping(entityType);
                configurationIndex = 0;
            }

            if (configurationIndex < entityTypeMapping.MappingFragments.Count)
            {
                fragment = entityTypeMapping.MappingFragments[configurationIndex];
            }
            else
            {
                if (MapInheritedProperties)
                {
                    throw Error.EntityMappingConfiguration_DuplicateMapInheritedProperties(entityType.Name);
                }
                else if (Properties == null)
                {
                    throw Error.EntityMappingConfiguration_DuplicateMappedProperties(entityType.Name);
                }
                else
                {
                    Properties.Each(
                        p =>
                            {
                                if (
                                    PropertyPathToEdmPropertyPath(p, entityType).Any(
                                        pp => !entityType.KeyProperties().Contains(pp.First())))
                                {
                                    throw Error.EntityMappingConfiguration_DuplicateMappedProperty(
                                        entityType.Name, p.ToString());
                                }
                            });
                }

                // Special case where they've asked for an extra table related to this type that only will include the PK columns
                // Uniquify: can be false, always move to a new table
                var templateTable = entityTypeMapping.MappingFragments[0].Table;

                var table = databaseMapping.Database.AddTable(templateTable.Name, templateTable);

                fragment
                    = EntityMappingOperations.CreateTypeMappingFragment(
                        entityTypeMapping,
                        entityTypeMapping.MappingFragments[0],
                        databaseMapping.Database.GetEntitySet(table));
            }
            return fragment;
        }
        private static EntityType FindParentTable(
            DbDatabaseMapping databaseMapping,
            EntityType fromTable,
            StorageEntityTypeMapping entityTypeMapping,
            EntityType toTable,
            bool isMappingInheritedProperties,
            int configurationIndex,
            int configurationCount,
            out bool isSplitting)
        {
            EntityType parentTable = null;
            isSplitting = false;
            // Check for entity splitting first, since splitting on a derived type in TPT/TPC will always have fromTable != toTable
            if (entityTypeMapping.UsesOtherTables(toTable)
                || configurationCount > 1)
            {
                if (configurationIndex != 0)
                {
                    // Entity Splitting case
                    parentTable = entityTypeMapping.GetPrimaryTable();
                    isSplitting = true;
                }
            }

            if (parentTable == null
                && fromTable != toTable
                && !isMappingInheritedProperties)
            {
                // TPT case
                var baseType = entityTypeMapping.EntityType.BaseType;
                while (baseType != null
                       && parentTable == null)
                {
                    // Traverse to first anscestor with a mapping
                    var baseMapping = databaseMapping.GetEntityTypeMappings((EntityType)baseType).FirstOrDefault();
                    if (baseMapping != null)
                    {
                        parentTable = baseMapping.GetPrimaryTable();
                    }
                    baseType = baseType.BaseType;
                }
            }

            return parentTable;
        }