private static ComplexType ConvertToComplexType(
            SchemaComplexType element,
            DbProviderManifest providerManifest,
            Converter.ConversionCache convertedItemCache,
            Dictionary <SchemaElement, GlobalItem> newGlobalItems)
        {
            ComplexType complexType = new ComplexType(element.Name, element.Namespace, Converter.GetDataSpace(providerManifest));

            newGlobalItems.Add((SchemaElement)element, (GlobalItem)complexType);
            foreach (StructuredProperty property in element.Properties)
            {
                complexType.AddMember((EdmMember)Converter.ConvertToProperty(property, providerManifest, convertedItemCache, newGlobalItems));
            }
            complexType.Abstract = element.IsAbstract;
            if (element.BaseType != null)
            {
                complexType.BaseType = (EdmType)Converter.LoadSchemaElement((System.Data.Entity.Core.SchemaObjectModel.SchemaType)element.BaseType, providerManifest, convertedItemCache, newGlobalItems);
            }
            if (element.Documentation != null)
            {
                complexType.Documentation = Converter.ConvertToDocumentation(element.Documentation);
            }
            Converter.AddOtherContent((SchemaElement)element, (MetadataItem)complexType);
            return(complexType);
        }
        public void Generate_should_flatten_complex_properties_to_columns()
        {
            var databaseMapping = CreateEmptyModel();
            var entityType = new EntityType("E", "N", DataSpace.CSpace);
            var complexType = new ComplexType("C");

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

            complexType.AddMember(property);
            entityType.AddComplexProperty("C1", complexType);
            var property1 = EdmProperty.Primitive("P2", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));

            entityType.AddMember(property1);
            var entitySet = databaseMapping.Model.AddEntitySet("ESet", entityType);
            var type = typeof(object);

            entityType.Annotations.SetClrType(type);

            new TableMappingGenerator(ProviderRegistry.Sql2008_ProviderManifest).Generate(entityType, databaseMapping);

            var entityTypeMappingFragment
                = databaseMapping.GetEntitySetMapping(entitySet).EntityTypeMappings.Single().MappingFragments.Single();

            Assert.Equal(2, entityTypeMappingFragment.ColumnMappings.Count());
            Assert.Equal(2, entityTypeMappingFragment.Table.Properties.Count());
        }
Beispiel #3
0
        /// <summary>
        /// Creates a new instance of the <see cref="ComplexType " /> type.
        /// </summary>
        /// <param name="name">The name of the complex type.</param>
        /// <param name="namespaceName">The namespace of the complex type.</param>
        /// <param name="dataSpace">The dataspace to which the complex type belongs to.</param>
        /// <param name="members">Members of the complex type.</param>
        /// <param name="metadataProperties">Metadata properties to be associated with the instance.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if either name, namespace or members argument is null.</exception>
        /// <returns>
        /// A new instance a the <see cref="ComplexType " /> type.
        /// </returns>
        /// <notes>
        /// The newly created <see cref="ComplexType " /> will be read only.
        /// </notes>
        public static ComplexType Create(
            string name,
            string namespaceName,
            DataSpace dataSpace,
            IEnumerable <EdmMember> members,
            IEnumerable <MetadataProperty> metadataProperties)
        {
            Check.NotEmpty(name, "name");
            Check.NotEmpty(namespaceName, "namespaceName");
            Check.NotNull(members, "members");

            var complexType = new ComplexType(name, namespaceName, dataSpace);

            foreach (var member in members)
            {
                complexType.AddMember(member);
            }

            if (metadataProperties != null)
            {
                complexType.AddMetadataProperties(metadataProperties);
            }

            complexType.SetReadOnly();
            return(complexType);
        }
        public void Can_generate_scalar_and_complex_properties_when_update()
        {
            var functionParameterMappingGenerator
                = new FunctionParameterMappingGenerator(ProviderRegistry.Sql2008_ProviderManifest);

            var property0 = new EdmProperty("P0");
            var property1 = new EdmProperty("P1");
            var property2 = new EdmProperty("P2");

            property2.SetStoreGeneratedPattern(StoreGeneratedPattern.Computed);
            property2.ConcurrencyMode = ConcurrencyMode.Fixed;

            var complexType = new ComplexType("CT", "N", DataSpace.CSpace);

            complexType.AddMember(property1);

            var complexProperty = EdmProperty.CreateComplex("C", complexType);

            var parameterBindings
                = functionParameterMappingGenerator
                    .Generate(
                        ModificationOperator.Update,
                        new[] { property0, complexProperty, property2 },
                        new[]
                            {
                                new ColumnMappingBuilder(new EdmProperty("C0"), new[] { property0 }),
                                new ColumnMappingBuilder(new EdmProperty("C_P1"), new[] { complexProperty, property1 }),
                                new ColumnMappingBuilder(new EdmProperty("C2"), new[] { property2 })
                            },
                        new List<EdmProperty>(),
                        useOriginalValues: true)
                    .ToList();

            Assert.Equal(3, parameterBindings.Count());

            var parameterBinding = parameterBindings.First();

            Assert.Equal("C0", parameterBinding.Parameter.Name);
            Assert.Same(property0, parameterBinding.MemberPath.Members.Single());
            Assert.Equal("String", parameterBinding.Parameter.TypeName);
            Assert.Equal(ParameterMode.In, parameterBinding.Parameter.Mode);
            Assert.False(parameterBinding.IsCurrent);

            parameterBinding = parameterBindings.ElementAt(1);

            Assert.Equal("C_P1", parameterBinding.Parameter.Name);
            Assert.Same(complexProperty, parameterBinding.MemberPath.Members.First());
            Assert.Same(property1, parameterBinding.MemberPath.Members.Last());
            Assert.Equal("String", parameterBinding.Parameter.TypeName);
            Assert.Equal(ParameterMode.In, parameterBinding.Parameter.Mode);
            Assert.False(parameterBinding.IsCurrent);

            parameterBinding = parameterBindings.Last();

            Assert.Equal("C2_Original", parameterBinding.Parameter.Name);
            Assert.Same(property2, parameterBinding.MemberPath.Members.Single());
            Assert.Equal("String", parameterBinding.Parameter.TypeName);
            Assert.Equal(ParameterMode.In, parameterBinding.Parameter.Mode);
            Assert.False(parameterBinding.IsCurrent);
        }
        public void Properties_list_should_be_live_on_reread()
        {
            var complexType = new ComplexType("C");

            Assert.Empty(complexType.Properties);

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

            complexType.AddMember(property);

            Assert.Equal(1, complexType.Properties.Count);
        }
        public void AddPrimitiveProperty_should_create_and_add_to_primitive_properties()
        {
            var complexType = new ComplexType("C");
            var property1 = EdmProperty.CreatePrimitive("Foo", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));

            complexType.AddMember(property1);
            var property = property1;

            Assert.NotNull(property);
            Assert.Equal("Foo", property.Name);
            Assert.True(complexType.Properties.Contains(property));
        }
Beispiel #7
0
        public void Properties_list_should_be_live_on_reread()
        {
            var complexType = new ComplexType("C");

            Assert.Empty(complexType.Properties);

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

            complexType.AddMember(property);

            Assert.Equal(1, complexType.Properties.Count);
        }
        public void GetPrimitiveProperty_should_return_correct_property()
        {
            var complexType = new ComplexType("C");
            var property1 = EdmProperty.CreatePrimitive("Foo", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));

            complexType.AddMember(property1);
            var property = property1;

            var foundProperty = complexType.Properties.SingleOrDefault(p => p.Name == "Foo");

            Assert.NotNull(foundProperty);
            Assert.Same(property, foundProperty);
        }
Beispiel #9
0
        private EdmModel CreateTestModel()
        {
            var model = new EdmModel(DataSpace.SSpace);

            var sqlManifest     = new SqlProviderManifest("2008");
            var stringTypeUsage = sqlManifest.GetStoreType(
                TypeUsage.CreateDefaultTypeUsage(
                    PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String)));

            var complexType = new ComplexType("Entity", "Unicorns420", DataSpace.SSpace);

            complexType.AddMember(new EdmProperty("NullableProperty", stringTypeUsage)
            {
                Nullable = true
            });
            complexType.AddMember(new EdmProperty("NonNullableProperty", stringTypeUsage)
            {
                Nullable = false
            });
            model.AddItem(complexType);

            return(model);
        }
        private static void AddBuiltInTypeProperties(
            BuiltInTypeKind builtInTypeKind,
            EdmProperty[] properties)
        {
            ComplexType builtInType = (ComplexType)MetadataItem.GetBuiltInType(builtInTypeKind);

            if (properties == null)
            {
                return;
            }
            for (int index = 0; index < properties.Length; ++index)
            {
                builtInType.AddMember((EdmMember)properties[index]);
            }
        }
        public void Map(
            PropertyInfo propertyInfo, ComplexType complexType,
            Func<ComplexTypeConfiguration> complexTypeConfiguration)
        {
            DebugCheck.NotNull(propertyInfo);
            DebugCheck.NotNull(complexType);

            var property = MapPrimitiveOrComplexOrEnumProperty(
                propertyInfo, complexTypeConfiguration, discoverComplexTypes: true);

            if (property != null)
            {
                complexType.AddMember(property);
            }
        }
        public void Configure_should_configure_properties()
        {
            var complexType = new ComplexType("C");

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

            complexType.AddMember(property1);
            var property = property1;
            var complexTypeConfiguration = new ComplexTypeConfiguration(typeof(object));
            var mockPropertyConfiguration = new Mock<PrimitivePropertyConfiguration>();
            var mockPropertyInfo = new MockPropertyInfo();
            complexTypeConfiguration.Property(new PropertyPath(mockPropertyInfo), () => mockPropertyConfiguration.Object);
            property.SetClrPropertyInfo(mockPropertyInfo);

            complexTypeConfiguration.Configure(complexType);

            mockPropertyConfiguration.Verify(p => p.Configure(property));
        }
        /// <summary>
        /// Creates a new instance of the <see cref="T:System.Data.Entity.Core.Metadata.Edm.ComplexType" /> type.
        /// </summary>
        /// <param name="name">The name of the complex type.</param>
        /// <param name="namespaceName">The namespace of the complex type.</param>
        /// <param name="dataSpace">The dataspace to which the complex type belongs to.</param>
        /// <param name="members">Members of the complex type.</param>
        /// <param name="metadataProperties">Metadata properties to be associated with the instance.</param>
        /// <exception cref="T:System.ArgumentNullException">Thrown if either name, namespace or members argument is null.</exception>
        /// <returns>
        /// A new instance a the <see cref="T:System.Data.Entity.Core.Metadata.Edm.ComplexType" /> type.
        /// </returns>
        /// <notes>
        /// The newly created <see cref="T:System.Data.Entity.Core.Metadata.Edm.ComplexType" /> will be read only.
        /// </notes>
        public static ComplexType Create(
            string name,
            string namespaceName,
            DataSpace dataSpace,
            IEnumerable <EdmMember> members,
            IEnumerable <MetadataProperty> metadataProperties)
        {
            Check.NotEmpty(name, nameof(name));
            Check.NotEmpty(namespaceName, nameof(namespaceName));
            Check.NotNull <IEnumerable <EdmMember> >(members, nameof(members));
            ComplexType complexType = new ComplexType(name, namespaceName, dataSpace);

            foreach (EdmMember member in members)
            {
                complexType.AddMember(member);
            }
            if (metadataProperties != null)
            {
                complexType.AddMetadataProperties(metadataProperties.ToList <MetadataProperty>());
            }
            complexType.SetReadOnly();
            return(complexType);
        }
Beispiel #14
0
        public void ComplexType_apply_should_set_correct_defaults_for_non_unicode_fixed_length_strings()
        {
            var entityType = new ComplexType("C");
            var property = EdmProperty.Primitive("P", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));
            property.IsFixedLength = true;
            property.IsUnicode = false;
            entityType.AddMember(property);

            (new PropertyMaxLengthConvention())
                .Apply(entityType, new DbModel(new EdmModel(DataSpace.CSpace), null));

            Assert.Equal(128, property.MaxLength);
            Assert.False(property.IsMaxLength);
        }
Beispiel #15
0
        public void WriteFunctionImportMappingElement_writes_result_mapping_for_non_composable_functions_mapped_explicitly_to_ComplexType()
        {
            var typeUsage =
                TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32));

            var complexTypeProperty1 = new EdmProperty("CTProperty1", typeUsage);
            var complexTypeProperty2 = new EdmProperty("CTProperty2", typeUsage);

            var complexType = new ComplexType("CT", "Ns", DataSpace.CSpace);

            complexType.AddMember(complexTypeProperty1);
            complexType.AddMember(complexTypeProperty2);

            var functionImport =
                new EdmFunction(
                    "f_c", "Ns", DataSpace.CSpace,
                    new EdmFunctionPayload
            {
                IsComposable     = false,
                IsFunctionImport = true,
                ReturnParameters =
                    new[]
                {
                    new FunctionParameter(
                        "ReturnValue",
                        TypeUsage.CreateDefaultTypeUsage(complexType.GetCollectionType()),
                        ParameterMode.ReturnValue)
                },
            });

            typeUsage = ProviderRegistry.Sql2008_ProviderManifest.GetStoreType(typeUsage);
            var rowTypeProperty1 = new EdmProperty("RTProperty1", typeUsage);
            var rowTypeProperty2 = new EdmProperty("RTProperty2", typeUsage);
            var rowType          = new RowType(new[] { rowTypeProperty1, rowTypeProperty2 });

            var storeFunction =
                new EdmFunction(
                    "f_s", "Ns.Store", DataSpace.SSpace,
                    new EdmFunctionPayload
            {
                IsComposable     = false,
                ReturnParameters =
                    new[]
                {
                    new FunctionParameter(
                        "Return",
                        TypeUsage.CreateDefaultTypeUsage(rowType),
                        ParameterMode.ReturnValue)
                },
            });

            var functionImportResultMapping = new FunctionImportResultMapping();

            functionImportResultMapping.AddTypeMapping(
                new FunctionImportComplexTypeMapping(
                    complexType,
                    new Collections.ObjectModel.Collection <FunctionImportReturnTypePropertyMapping>()
            {
                new FunctionImportReturnTypeScalarPropertyMapping("CTProperty1", "RTProperty1"),
                new FunctionImportReturnTypeScalarPropertyMapping("CTProperty2", "RTProperty2")
            }
                    ));

            var mappingItemCollection =
                new StorageMappingItemCollection(
                    new EdmItemCollection(EdmModel.CreateConceptualModel()),
                    new StoreItemCollection(
                        EdmModel.CreateStoreModel(ProviderRegistry.Sql2008_ProviderInfo, ProviderRegistry.Sql2008_ProviderManifest)),
                    new string[0]);

            var containerMapping = new EntityContainerMapping(
                new EntityContainer("C", DataSpace.CSpace), new EntityContainer("S", DataSpace.SSpace), mappingItemCollection, false);

            var functionImportMapping =
                new FunctionImportMappingNonComposable(
                    functionImport,
                    storeFunction,
                    new []
            {
                functionImportResultMapping
            },
                    containerMapping);

            containerMapping.AddFunctionImportMapping(functionImportMapping);

            var fixture = new Fixture();

            fixture.Writer.WriteFunctionImportMappingElement(functionImportMapping);
            Assert.Equal(
                @"<FunctionImportMapping FunctionName=""Ns.Store.f_s"" FunctionImportName=""f_c"">
  <ResultMapping>
    <ComplexTypeMapping TypeName=""Ns.CT"">
      <ScalarProperty Name=""CTProperty1"" ColumnName=""RTProperty1"" />
      <ScalarProperty Name=""CTProperty2"" ColumnName=""RTProperty2"" />
    </ComplexTypeMapping>
  </ResultMapping>
</FunctionImportMapping>",
                fixture.ToString());
        }
        public void TranslateColumnMap_returns_correct_columntypes_and_nullablecolumns_for_complex_types()
        {
            var metadataWorkspaceMock = new Mock<MetadataWorkspace>();
            metadataWorkspaceMock.Setup(m => m.GetQueryCacheManager()).Returns(QueryCacheManager.Create());

            var cSpaceComplexType = new ComplexType("C");
            var intTypeUsage = TypeUsage.Create(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32), new FacetValues { Nullable = false });
            cSpaceComplexType.AddMember(new EdmProperty("Id", intTypeUsage));
            cSpaceComplexType.AddMember(new EdmProperty("Count", intTypeUsage));

            var complexTypeUsage = TypeUsage.Create(cSpaceComplexType);
            var recordMap = new ComplexTypeColumnMap(
                complexTypeUsage, "E",
                new[] { new ScalarColumnMap(cSpaceComplexType.Properties[0].TypeUsage, cSpaceComplexType.Properties[0].Name, 0, 0) },
                new ScalarColumnMap(cSpaceComplexType.Properties[1].TypeUsage, cSpaceComplexType.Properties[1].Name, 0, 1));
            var collectionMap = new SimpleCollectionColumnMap(
                complexTypeUsage, "MockCollectionType", recordMap, null, null);
            
            metadataWorkspaceMock.Setup(m => m.GetItem<EdmType>(It.IsAny<string>(), DataSpace.OSpace))
                .Returns(new CodeFirstOSpaceTypeFactory().TryCreateType(typeof(SimpleEntity), cSpaceComplexType));

            var factory =
                new Translator().TranslateColumnMap<object>(
                    collectionMap, metadataWorkspaceMock.Object, new SpanIndex(), MergeOption.NoTracking, streaming: false, valueLayer: false);
            Assert.NotNull(factory);

            Assert.Equal(new[] { typeof(int), null }, factory.ColumnTypes);
            Assert.Equal(new[] { true, true }, factory.NullableColumns);
        }
Beispiel #17
0
        public void WriteEntityContainerMappingElement_should_write_function_import_elements_mapped_to_ComplexType()
        {
            var typeUsage =
                TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32));

            var complexTypeProperty1 = new EdmProperty("CTProperty1", typeUsage);
            var complexTypeProperty2 = new EdmProperty("CTProperty2", typeUsage);

            var complexType = new ComplexType("CT", "Ns", DataSpace.CSpace);

            complexType.AddMember(complexTypeProperty1);
            complexType.AddMember(complexTypeProperty2);

            var functionImport =
                new EdmFunction(
                    "f_c", "Ns", DataSpace.CSpace,
                    new EdmFunctionPayload
            {
                IsComposable     = true,
                IsFunctionImport = true,
                ReturnParameters =
                    new[]
                {
                    new FunctionParameter(
                        "ReturnValue",
                        TypeUsage.CreateDefaultTypeUsage(complexType.GetCollectionType()),
                        ParameterMode.ReturnValue)
                },
                Parameters =
                    new[]
                {
                    new FunctionParameter("param", typeUsage, ParameterMode.Out)
                }
            });

            typeUsage = ProviderRegistry.Sql2008_ProviderManifest.GetStoreType(typeUsage);
            var rowTypeProperty1 = new EdmProperty("RTProperty1", typeUsage);
            var rowTypeProperty2 = new EdmProperty("RTProperty2", typeUsage);
            var rowType          = new RowType(new[] { rowTypeProperty1, rowTypeProperty2 });

            var storeFunction =
                new EdmFunction(
                    "f_s", "Ns.Store", DataSpace.SSpace,
                    new EdmFunctionPayload
            {
                ReturnParameters =
                    new[]
                {
                    new FunctionParameter(
                        "Return",
                        TypeUsage.CreateDefaultTypeUsage(rowType),
                        ParameterMode.ReturnValue)
                },
                Parameters =
                    new[]
                {
                    new FunctionParameter("param", typeUsage, ParameterMode.Out)
                }
            });

            var structuralTypeMapping =
                new Tuple <StructuralType, List <ConditionPropertyMapping>, List <PropertyMapping> >(
                    complexType, new List <ConditionPropertyMapping>(), new List <PropertyMapping>());

            structuralTypeMapping.Item3.Add(new ScalarPropertyMapping(complexTypeProperty1, rowTypeProperty1));
            structuralTypeMapping.Item3.Add(new ScalarPropertyMapping(complexTypeProperty2, rowTypeProperty2));

            var functionImportMapping = new FunctionImportMappingComposable(
                functionImport,
                storeFunction,
                new List <Tuple <StructuralType, List <ConditionPropertyMapping>, List <PropertyMapping> > >
            {
                structuralTypeMapping
            });

            var containerMapping = new EntityContainerMapping(new EntityContainer("C", DataSpace.SSpace));

            containerMapping.AddFunctionImportMapping(functionImportMapping);

            var fixture = new Fixture();

            fixture.Writer.WriteEntityContainerMappingElement(containerMapping);

            Assert.Equal(
                @"<EntityContainerMapping StorageEntityContainer="""" CdmEntityContainer=""C"">
  <FunctionImportMapping FunctionName=""Ns.Store.f_s"" FunctionImportName=""f_c"">
    <ResultMapping>
      <ComplexTypeMapping TypeName=""Ns.CT"">
        <ScalarProperty Name=""CTProperty1"" ColumnName=""RTProperty1"" />
        <ScalarProperty Name=""CTProperty2"" ColumnName=""RTProperty2"" />
      </ComplexTypeMapping>
    </ResultMapping>
  </FunctionImportMapping>
</EntityContainerMapping>",
                fixture.ToString());
        }
Beispiel #18
0
        public void WriteFunctionImportMappingElement_does_not_write_result_mapping_for_non_composable_functions_mapped_implicitly()
        {
            var typeUsage =
                TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32));

            var complexTypeProperty1 = new EdmProperty("CTProperty1", typeUsage);
            var complexTypeProperty2 = new EdmProperty("CTProperty2", typeUsage);

            var complexType = new ComplexType("CT", "Ns", DataSpace.CSpace);

            complexType.AddMember(complexTypeProperty1);
            complexType.AddMember(complexTypeProperty2);

            var functionImport =
                new EdmFunction(
                    "f_c", "Ns", DataSpace.CSpace,
                    new EdmFunctionPayload
            {
                IsComposable     = false,
                IsFunctionImport = true,
                ReturnParameters =
                    new[]
                {
                    new FunctionParameter(
                        "ReturnValue",
                        TypeUsage.CreateDefaultTypeUsage(complexType.GetCollectionType()),
                        ParameterMode.ReturnValue)
                },
            });

            typeUsage = ProviderRegistry.Sql2008_ProviderManifest.GetStoreType(typeUsage);
            var rowTypeProperty1 = new EdmProperty("RTProperty1", typeUsage);
            var rowTypeProperty2 = new EdmProperty("RTProperty2", typeUsage);
            var rowType          = new RowType(new[] { rowTypeProperty1, rowTypeProperty2 });

            var storeFunction =
                new EdmFunction(
                    "f_s", "Ns.Store", DataSpace.SSpace,
                    new EdmFunctionPayload
            {
                IsComposable     = false,
                ReturnParameters =
                    new[]
                {
                    new FunctionParameter(
                        "Return",
                        TypeUsage.CreateDefaultTypeUsage(rowType),
                        ParameterMode.ReturnValue)
                },
            });

            var functionImportMapping =
                new FunctionImportMappingNonComposable(
                    functionImport,
                    storeFunction,
                    new FunctionImportResultMapping[0],
                    new EntityContainerMapping(new EntityContainer("C", DataSpace.SSpace)));

            var fixture = new Fixture();

            fixture.Writer.WriteFunctionImportMappingElement(functionImportMapping);
            Assert.Equal(
                @"<FunctionImportMapping FunctionName=""Ns.Store.f_s"" FunctionImportName=""f_c"" />",
                fixture.ToString());
        }
        public void ComplexType_apply_should_set_correct_defaults_for_non_unicode_fixed_length_strings()
        {
            var complexType = new ComplexType("C");
            var property = EdmProperty.CreatePrimitive("P", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));
            property.IsFixedLength = true;
            property.IsUnicode = false;
            complexType.AddMember(property);

            (new SqlCePropertyMaxLengthConvention())
                .Apply(complexType, CreateDbModel());

            Assert.Equal(4000, property.MaxLength);
        }
        public void ComplexType_apply_should_set_correct_defaults_for_fixed_length_binary()
        {
            var entityType = new ComplexType("C");
            var property = EdmProperty.Primitive("P", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Binary));
            property.IsFixedLength = true;
            entityType.AddMember(property);

            ((IEdmConvention<ComplexType>)new PropertyMaxLengthConvention())
                .Apply(entityType, new EdmModel(DataSpace.CSpace));

            Assert.Null(property.IsUnicode);
            Assert.Equal(128, property.MaxLength);
            Assert.False(property.IsMaxLength);
        }
        public void WriteFunctionImportMappingElement_does_not_write_result_mapping_for_non_composable_functions_mapped_implicitly()
        {
            var typeUsage =
                TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32));

            var complexTypeProperty1 = new EdmProperty("CTProperty1", typeUsage);
            var complexTypeProperty2 = new EdmProperty("CTProperty2", typeUsage);

            var complexType = new ComplexType("CT", "Ns", DataSpace.CSpace);
            complexType.AddMember(complexTypeProperty1);
            complexType.AddMember(complexTypeProperty2);

            var functionImport =
                new EdmFunction(
                    "f_c", "Ns", DataSpace.CSpace,
                    new EdmFunctionPayload
                    {
                        IsComposable = false,
                        IsFunctionImport = true,
                        ReturnParameters =
                            new[]
                                    {
                                        new FunctionParameter(
                                            "ReturnValue",
                                            TypeUsage.CreateDefaultTypeUsage(complexType.GetCollectionType()),
                                            ParameterMode.ReturnValue)
                                    },
                    });

            typeUsage = ProviderRegistry.Sql2008_ProviderManifest.GetStoreType(typeUsage);
            var rowTypeProperty1 = new EdmProperty("RTProperty1", typeUsage);
            var rowTypeProperty2 = new EdmProperty("RTProperty2", typeUsage);
            var rowType = new RowType(new[] { rowTypeProperty1, rowTypeProperty2 });

            var storeFunction =
                new EdmFunction(
                    "f_s", "Ns.Store", DataSpace.SSpace,
                    new EdmFunctionPayload
                    {
                        IsComposable = false,
                        ReturnParameters =
                            new[]
                                    {
                                        new FunctionParameter(
                                            "Return",
                                            TypeUsage.CreateDefaultTypeUsage(rowType),
                                            ParameterMode.ReturnValue)
                                    },
                    });

            var functionImportMapping = 
                new FunctionImportMappingNonComposable(
                   functionImport,
                   storeFunction,
                   new FunctionImportResultMapping[0],
                   new EntityContainerMapping(new EntityContainer("C", DataSpace.SSpace)));

            var fixture = new Fixture();
            fixture.Writer.WriteFunctionImportMappingElement(functionImportMapping);
            Assert.Equal(
                @"<FunctionImportMapping FunctionName=""Ns.Store.f_s"" FunctionImportName=""f_c"" />",
                fixture.ToString());
        }
        public void WriteFunctionImportMappingElement_writes_result_mapping_for_non_composable_functions_mapped_explicitly_to_ComplexType()
        {
            var typeUsage =
                TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32));

            var complexTypeProperty1 = new EdmProperty("CTProperty1", typeUsage);
            var complexTypeProperty2 = new EdmProperty("CTProperty2", typeUsage);

            var complexType = new ComplexType("CT", "Ns", DataSpace.CSpace);
            complexType.AddMember(complexTypeProperty1);
            complexType.AddMember(complexTypeProperty2);

            var functionImport =
                new EdmFunction(
                    "f_c", "Ns", DataSpace.CSpace,
                    new EdmFunctionPayload
                    {
                        IsComposable = false,
                        IsFunctionImport = true,
                        ReturnParameters =
                            new[]
                                    {
                                        new FunctionParameter(
                                            "ReturnValue",
                                            TypeUsage.CreateDefaultTypeUsage(complexType.GetCollectionType()),
                                            ParameterMode.ReturnValue)
                                    },
                    });

            typeUsage = ProviderRegistry.Sql2008_ProviderManifest.GetStoreType(typeUsage);
            var rowTypeProperty1 = new EdmProperty("RTProperty1", typeUsage);
            var rowTypeProperty2 = new EdmProperty("RTProperty2", typeUsage);
            var rowType = new RowType(new[] { rowTypeProperty1, rowTypeProperty2 });

            var storeFunction =
                new EdmFunction(
                    "f_s", "Ns.Store", DataSpace.SSpace,
                    new EdmFunctionPayload
                    {
                        IsComposable = false,
                        ReturnParameters =
                            new[]
                                    {
                                        new FunctionParameter(
                                            "Return",
                                            TypeUsage.CreateDefaultTypeUsage(rowType),
                                            ParameterMode.ReturnValue)
                                    },
                    });

            var functionImportResultMapping = new FunctionImportResultMapping();
            functionImportResultMapping.AddTypeMapping(
                new FunctionImportComplexTypeMapping(
                    complexType,
                    new Collections.ObjectModel.Collection<FunctionImportReturnTypePropertyMapping>()
                    {
                        new FunctionImportReturnTypeScalarPropertyMapping("CTProperty1", "RTProperty1"),
                        new FunctionImportReturnTypeScalarPropertyMapping("CTProperty2", "RTProperty2")
                    }
                ));

            var mappingItemCollection = 
                new StorageMappingItemCollection(
                    new EdmItemCollection(EdmModel.CreateConceptualModel()), 
                    new StoreItemCollection(
                        EdmModel.CreateStoreModel(ProviderRegistry.Sql2008_ProviderInfo, ProviderRegistry.Sql2008_ProviderManifest)), 
                    new string[0]);

            var containerMapping = new EntityContainerMapping(
                new EntityContainer("C", DataSpace.CSpace), new EntityContainer("S", DataSpace.SSpace), mappingItemCollection, false);

            var functionImportMapping =
                new FunctionImportMappingNonComposable(
                   functionImport,
                   storeFunction,
                   new []
                   {
                       functionImportResultMapping
                   },
                   containerMapping);

            containerMapping.AddFunctionImportMapping(functionImportMapping);

            var fixture = new Fixture();
            fixture.Writer.WriteFunctionImportMappingElement(functionImportMapping);
            Assert.Equal(
                @"<FunctionImportMapping FunctionName=""Ns.Store.f_s"" FunctionImportName=""f_c"">
  <ResultMapping>
    <ComplexTypeMapping TypeName=""Ns.CT"">
      <ScalarProperty Name=""CTProperty1"" ColumnName=""RTProperty1"" />
      <ScalarProperty Name=""CTProperty2"" ColumnName=""RTProperty2"" />
    </ComplexTypeMapping>
  </ResultMapping>
</FunctionImportMapping>",
                fixture.ToString());
        }
        public void ComplexType_apply_should_set_correct_defaults_for_unconfigured_strings()
        {
            var entityType = new ComplexType("C");
            var property = EdmProperty.Primitive("P", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));
            entityType.AddMember(property);

            ((IEdmConvention<ComplexType>)new PropertyMaxLengthConvention())
                .Apply(entityType, new EdmModel(DataSpace.CSpace));

            Assert.Equal(true, property.IsUnicode);
            Assert.Equal(false, property.IsFixedLength);
            Assert.Null(property.MaxLength);
            Assert.Equal(true, property.IsMaxLength);
        }
        public void WriteEntityContainerMappingElement_should_write_function_import_elements_mapped_to_ComplexType()
        {
            var typeUsage = 
                TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32));

            var complexTypeProperty1 = new EdmProperty("CTProperty1", typeUsage);
            var complexTypeProperty2 = new EdmProperty("CTProperty2", typeUsage);

            var complexType = new ComplexType("CT", "Ns", DataSpace.CSpace);
            complexType.AddMember(complexTypeProperty1);
            complexType.AddMember(complexTypeProperty2);

            var functionImport =
                new EdmFunction(
                    "f_c", "Ns", DataSpace.CSpace,
                    new EdmFunctionPayload
                        {
                            IsComposable = true,
                            IsFunctionImport = true,
                            ReturnParameters =
                                new[]
                                    {
                                        new FunctionParameter(
                                            "ReturnValue",
                                            TypeUsage.CreateDefaultTypeUsage(complexType.GetCollectionType()),
                                            ParameterMode.ReturnValue)
                                    },
                            Parameters =
                                new[]
                                    {
                                        new FunctionParameter("param", typeUsage, ParameterMode.Out)
                                    }
                        });

            typeUsage = ProviderRegistry.Sql2008_ProviderManifest.GetStoreType(typeUsage);
            var rowTypeProperty1 = new EdmProperty("RTProperty1", typeUsage);
            var rowTypeProperty2 = new EdmProperty("RTProperty2", typeUsage);
            var rowType = new RowType(new[] { rowTypeProperty1, rowTypeProperty2 });

            var storeFunction =
                new EdmFunction(
                    "f_s", "Ns.Store", DataSpace.SSpace,
                    new EdmFunctionPayload
                        {
                            ReturnParameters =
                                new[]
                                    {
                                        new FunctionParameter(
                                            "Return",
                                            TypeUsage.CreateDefaultTypeUsage(rowType),
                                            ParameterMode.ReturnValue)
                                    },
                            Parameters =
                                new[]
                                    {
                                        new FunctionParameter("param", typeUsage, ParameterMode.Out)
                                    }
                        });

            var structuralTypeMapping =
                new Tuple<StructuralType, List<ConditionPropertyMapping>, List<PropertyMapping>>(
                    complexType, new List<ConditionPropertyMapping>(), new List<PropertyMapping>());

            structuralTypeMapping.Item3.Add(new ScalarPropertyMapping(complexTypeProperty1, rowTypeProperty1));
            structuralTypeMapping.Item3.Add(new ScalarPropertyMapping(complexTypeProperty2, rowTypeProperty2));

            var functionImportMapping = new FunctionImportMappingComposable(
                functionImport,
                storeFunction,
                new List<Tuple<StructuralType, List<ConditionPropertyMapping>, List<PropertyMapping>>>
                    {
                        structuralTypeMapping
                    });

            var containerMapping = new EntityContainerMapping(new EntityContainer("C", DataSpace.SSpace));
            containerMapping.AddFunctionImportMapping(functionImportMapping);

            var fixture = new Fixture();
            fixture.Writer.WriteEntityContainerMappingElement(containerMapping);

            Assert.Equal(
                @"<EntityContainerMapping StorageEntityContainer="""" CdmEntityContainer=""C"">
  <FunctionImportMapping FunctionName=""Ns.Store.f_s"" FunctionImportName=""f_c"">
    <ResultMapping>
      <ComplexTypeMapping TypeName=""Ns.CT"">
        <ScalarProperty Name=""CTProperty1"" ColumnName=""RTProperty1"" />
        <ScalarProperty Name=""CTProperty2"" ColumnName=""RTProperty2"" />
      </ComplexTypeMapping>
    </ResultMapping>
  </FunctionImportMapping>
</EntityContainerMapping>",
                fixture.ToString());
        }
        public void ComplexType_apply_should_set_correct_defaults_for_fixed_length_binary()
        {
            var entityType = new ComplexType("C");
            var property = EdmProperty.Primitive("P", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));
            property.IsFixedLength = true;
            entityType.AddMember(property);

            ((IEdmConvention<ComplexType>)new SqlCePropertyMaxLengthConvention())
                .Apply(entityType, CreateEdmModel());

            Assert.Null(property.IsUnicode);
            Assert.Equal(4000, property.MaxLength);
        }
        public void ComplexType_apply_should_set_correct_defaults_for_unconfigured_binary()
        {
            var entityType = new ComplexType("C");
            var property = EdmProperty.CreatePrimitive("P", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Binary));
            entityType.AddMember(property);

            (new PropertyMaxLengthConvention())
                .Apply(entityType, new DbModel(new EdmModel(DataSpace.CSpace), null));

            Assert.Null(property.IsUnicode);
            Assert.Equal(false, property.IsFixedLength);
            Assert.Null(property.MaxLength);
        }
        /// <summary>
        ///     Creates a new instance of the <see cref="ComplexType " /> type.
        /// </summary>
        /// <param name="name">The name of the complex type.</param>
        /// <param name="namespaceName">The namespace of the complex type.</param>
        /// <param name="dataSpace">The dataspace to which the complex type belongs to.</param>
        /// <param name="members">Members of the complex type.</param>
        /// <param name="metadataProperties">Metadata properties to be associated with the instance.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if either name, namespace or members argument is null.</exception>
        /// <returns>
        ///     A new instance a the <see cref="ComplexType " /> type.
        /// </returns>
        /// <notes>
        ///     The newly created <see cref="ComplexType " /> will be read only.
        /// </notes>
        public static ComplexType Create(
            string name,
            string namespaceName,
            DataSpace dataSpace,
            IEnumerable<EdmMember> members,
            IEnumerable<MetadataProperty> metadataProperties)
        {
            Check.NotNull(name, "name");
            Check.NotNull(namespaceName, "namespaceName");
            Check.NotNull(members, "members");

            var complexType = new ComplexType(name, namespaceName, dataSpace);

            foreach (var member in members)
            {
                complexType.AddMember(member);
            }

            if (metadataProperties != null)
            {
                complexType.AddMetadataProperties(metadataProperties.ToList());
            }

            complexType.SetReadOnly();
            return complexType;
        }
        public void ComplexType_apply_should_set_given_value_for_fixed_length_binary()
        {
            var complexType = new ComplexType("C");
            var property = EdmProperty.CreatePrimitive("P", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));
            property.IsFixedLength = true;
            complexType.AddMember(property);

            (new SqlCePropertyMaxLengthConvention(2000)).Apply(complexType, CreateDbModel());

            Assert.Null(property.IsUnicode);
            Assert.Equal(2000, property.MaxLength);
        }
        private EdmModel CreateTestModel()
        {
            var model = new EdmModel(DataSpace.SSpace);

            var sqlManifest = new SqlProviderManifest("2008");
            var stringTypeUsage = sqlManifest.GetStoreType(
                TypeUsage.CreateDefaultTypeUsage(
                    PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String)));

            var complexType = new ComplexType("Entity", "Unicorns420", DataSpace.SSpace);
            complexType.AddMember(new EdmProperty("NullableProperty", stringTypeUsage) { Nullable = true });
            complexType.AddMember(new EdmProperty("NonNullableProperty", stringTypeUsage) { Nullable = false });
            model.AddItem(complexType);

            return model;
        }
        public void ComplexType_apply_should_set_given_value_for_unconfigured_strings()
        {
            var complexType = new ComplexType("C");
            var property = EdmProperty.CreatePrimitive("P", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));
            complexType.AddMember(property);

            (new SqlCePropertyMaxLengthConvention(2000)).Apply(complexType, CreateDbModel());

            Assert.Equal(2000, property.MaxLength);
        }
        /// <summary>
        /// Converts an complex type from SOM to metadata
        /// </summary>
        /// <param name="element">The SOM element to process</param>
        /// <param name="providerManifest">The provider manifest to be used for conversion</param>
        /// <param name="convertedItemCache">The item collection for currently existing metadata objects</param>
        /// <param name="newGlobalItems">The new GlobalItem objects that are created as a result of this conversion</param>
        /// <returns>The complex type object resulting from the convert</returns>
        private static ComplexType ConvertToComplexType(
            Som.SchemaComplexType element,
            DbProviderManifest providerManifest,
            ConversionCache convertedItemCache,
            Dictionary<Som.SchemaElement, GlobalItem> newGlobalItems)
        {
            var complexType = new ComplexType(
                element.Name,
                element.Namespace,
                GetDataSpace(providerManifest));
            newGlobalItems.Add(element, complexType);

            foreach (var somProperty in element.Properties)
            {
                complexType.AddMember(
                    ConvertToProperty(
                        somProperty,
                        providerManifest,
                        convertedItemCache,
                        newGlobalItems));
            }

            // set the abstract and sealed type values for the entity type
            complexType.Abstract = element.IsAbstract;

            if (element.BaseType != null)
            {
                complexType.BaseType = (EdmType)(LoadSchemaElement(
                    element.BaseType,
                    providerManifest,
                    convertedItemCache,
                    newGlobalItems));
            }

            // Extract the optional Documentation
            if (element.Documentation != null)
            {
                complexType.Documentation = ConvertToDocumentation(element.Documentation);
            }
            AddOtherContent(element, complexType);

            return complexType;
        }
        public void ComplexType_apply_should_set_correct_defaults_for_unconfigured_strings()
        {
            var entityType = new ComplexType("C");
            var property = EdmProperty.Primitive("P", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));
            entityType.AddMember(property);

            ((IEdmConvention<ComplexType>)new SqlCePropertyMaxLengthConvention())
                .Apply(entityType, CreateEdmModel());

            Assert.Equal(4000, property.MaxLength);
        }
        public void Generate_should_throw_when_circular_complex_property()
        {
            var functionParameterMappingGenerator
                = new FunctionParameterMappingGenerator(ProviderRegistry.Sql2008_ProviderManifest);

            var complexType = new ComplexType("CT", "N", DataSpace.CSpace);
            complexType.AddMember(EdmProperty.CreateComplex("C1", complexType));

            Assert.Equal(
                Strings.CircularComplexTypeHierarchy,
                Assert.Throws<InvalidOperationException>(
                    () => functionParameterMappingGenerator
                              .Generate(
                                  ModificationOperator.Insert,
                                  new[] { EdmProperty.CreateComplex("C0", complexType) },
                                  new ColumnMappingBuilder[0],
                                  new List<EdmProperty>())
                              .ToList()).Message);
        }