コード例 #1
0
        public override Task<ReverseEngineerFiles> WriteCodeAsync(
            ModelConfiguration modelConfiguration, 
            string outputPath, 
            string dbContextClassName,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            Check.NotNull(modelConfiguration, nameof(modelConfiguration));
            Check.NotEmpty(outputPath, nameof(outputPath));
            Check.NotEmpty(dbContextClassName, nameof(dbContextClassName));

            cancellationToken.ThrowIfCancellationRequested();

            var resultingFiles = new ReverseEngineerFiles();

            var generatedCode = DbContextWriter.WriteCode(modelConfiguration);

            // output DbContext .cs file
            var dbContextFileName = dbContextClassName + FileExtension;
            var dbContextFileFullPath = FileService.OutputFile(
                outputPath, dbContextFileName, generatedCode);
            resultingFiles.ContextFile = dbContextFileFullPath;

            foreach (var entityConfig in modelConfiguration.EntityConfigurations)
            {
                generatedCode = EntityTypeWriter.WriteCode(entityConfig);

                // output EntityType poco .cs file
                var entityTypeFileName = entityConfig.EntityType.DisplayName() + FileExtension;
                var entityTypeFileFullPath = FileService.OutputFile(
                    outputPath, entityTypeFileName, generatedCode);
                resultingFiles.EntityTypeFiles.Add(entityTypeFileFullPath);
            }

            return Task.FromResult(resultingFiles);
        }
コード例 #2
0
        public void Add_entity_configuration_should_add_to_model_configuration()
        {
            var modelConfiguration = new ModelConfiguration();
            var entityConfiguration = new EntityTypeConfiguration<object>();

            new ConfigurationRegistrar(modelConfiguration).Add(entityConfiguration);

            Assert.Same(entityConfiguration.Configuration, modelConfiguration.Entity(typeof(object)));
        }
コード例 #3
0
        public void Add_complex_type_configuration_should_add_to_model_configuration()
        {
            var modelConfiguration = new ModelConfiguration();
            var complexTypeConfiguration = new ComplexTypeConfiguration<object>();

            new ConfigurationRegistrar(modelConfiguration).Add(complexTypeConfiguration);

            Assert.Same(complexTypeConfiguration.Configuration, modelConfiguration.ComplexType(typeof(object)));
        }
コード例 #4
0
        public void Get_configured_types_should_return_types()
        {
            var modelConfiguration = new ModelConfiguration();
            var configurationRegistrar
                = new ConfigurationRegistrar(modelConfiguration)
                    .Add(new ComplexTypeConfiguration<object>())
                    .Add(new EntityTypeConfiguration<string>());

            Assert.Equal(2, configurationRegistrar.GetConfiguredTypes().Count());
        }
コード例 #5
0
        public void GetConfiguredProperties_should_return_all_configured_properties()
        {
            var modelConfiguration = new ModelConfiguration();
            var mockType = new MockType();
            var mockPropertyInfo = new MockPropertyInfo(typeof(string), "S");

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

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

            Assert.Same(mockPropertyInfo.Object, modelConfiguration.GetConfiguredProperties(mockType).Single());
        }
コード例 #6
0
        public void IsIgnoredProperty_should_return_true_if_property_is_ignored()
        {
            var modelConfiguration = new ModelConfiguration();
            var mockType = new MockType();
            var mockPropertyInfo = new MockPropertyInfo(typeof(string), "S");

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

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

            Assert.True(modelConfiguration.IsIgnoredProperty(mockType, mockPropertyInfo));
        }
コード例 #7
0
        public void ProccessActions()
        {
            if(_start==null || _resault==null)
                return;

            ModelConfiguration mc = new ModelConfiguration(_start);

            for (int i = 0; i < _actions.Count; i++)
            {
                mc = mc*_actions[i];
            }
            _resault.CopyFrom(mc);
        }
コード例 #8
0
        public void AddFromAssembly_should_add_all_configuration_to_model_configuration()
        {
            var modelConfiguration = new ModelConfiguration();

            new ConfigurationRegistrar(modelConfiguration).AddFromAssembly(CreateDynamicAssemblyWithStructuralTypeConfigurations());

            Assert.Equal(3, modelConfiguration.ComplexTypes.Count());
            Assert.Equal(3, modelConfiguration.Entities.Count());
            Assert.Equal(1, modelConfiguration.ConfiguredTypes.Count(t => t.Name == "Entity1"));
            Assert.Equal(1, modelConfiguration.ConfiguredTypes.Count(t => t.Name == "Complex1"));
            Assert.Equal(1, modelConfiguration.ConfiguredTypes.Count(t => t.Name == "Entity2"));
            Assert.Equal(1, modelConfiguration.ConfiguredTypes.Count(t => t.Name == "Complex2"));
            Assert.Equal(1, modelConfiguration.ConfiguredTypes.Count(t => t.Name == "Entity3"));
            Assert.Equal(1, modelConfiguration.ConfiguredTypes.Count(t => t.Name == "Complex3"));
        }
        public void HasConstraint_is_noop_when_set_on_inverse()
        {
            var modelConfiguration        = new ModelConfiguration();
            var inverseNavigationProperty = typeof(LightweighEntity).GetProperty(
                "PrivateNavigationProperty", BindingFlags.Instance | BindingFlags.NonPublic);

            modelConfiguration.Entity(typeof(LightweighEntity))
            .Navigation(inverseNavigationProperty)
            .Constraint = IndependentConstraintConfiguration.Instance;
            var configuration =
                new NavigationPropertyConfiguration(
                    typeof(LightweighEntity).GetProperty("ValidNavigationProperty"));

            configuration.InverseNavigationProperty = inverseNavigationProperty;
            var lightweightConfiguration = new ConventionNavigationPropertyConfiguration(configuration, modelConfiguration);

            lightweightConfiguration.HasConstraint <ForeignKeyConstraintConfiguration>();
            Assert.Null(configuration.Constraint);
        }
コード例 #10
0
        public void HasInverseNavigationProperty_sets_the_InverseNavigationProperty()
        {
            var navigationProperty       = typeof(LightweighEntity).GetDeclaredProperty("ValidNavigationProperty");
            var configuration            = new NavigationPropertyConfiguration(navigationProperty);
            var modelConfiguration       = new ModelConfiguration();
            var lightweightConfiguration = new ConventionNavigationPropertyConfiguration(configuration, modelConfiguration);

            var inverseNavigationProperty1 =
                typeof(LightweighEntity).GetDeclaredProperty("ValidInverseNavigationProperty");

            lightweightConfiguration.HasInverseNavigationProperty(p => inverseNavigationProperty1);
            Assert.Same(inverseNavigationProperty1, configuration.InverseNavigationProperty);

            var inverseNavigationProperty2 = typeof(LightweighEntity).GetDeclaredProperty("PrivateNavigationProperty");

            configuration.InverseNavigationProperty = inverseNavigationProperty2;
            lightweightConfiguration.HasInverseNavigationProperty(p => inverseNavigationProperty1);
            Assert.Same(inverseNavigationProperty2, configuration.InverseNavigationProperty);
        }
コード例 #11
0
            public void Does_not_invoke_action_and_short_circuts_when_first_predicate_false()
            {
                var lastPredicateInvoked = false;
                var actionInvoked        = false;
                var convention           = new TypeConvention(
                    new Func <Type, bool>[]
                {
                    t => false,
                    t => lastPredicateInvoked = true
                },
                    c => actionInvoked = true);
                var type          = new MockType();
                var configuration = new ModelConfiguration();

                convention.Apply(type, configuration);

                Assert.False(lastPredicateInvoked);
                Assert.False(actionInvoked);
            }
        public void Apply_finds_inverse_when_many_to_many()
        {
            var mockTypeA        = new MockType("A");
            var mockTypeB        = new MockType("B").Property(mockTypeA.AsCollection(), "As");
            var mockPropertyInfo = mockTypeB.GetProperty("As");

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

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

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

            Assert.Same(mockTypeA.GetProperty("Bs"), navigationPropertyConfiguration.InverseNavigationProperty);
        }
コード例 #13
0
        public void MapComplexType_should_throw_for_new_type_if_complex_type_with_same_simple_name_already_used()
        {
            var model = new EdmModel(DataSpace.CSpace);

            var mockType1 = new MockType("Foo");
            var mockType2 = new MockType("Foo");

            var modelConfiguration = new ModelConfiguration();

            modelConfiguration.ComplexType(mockType1);
            modelConfiguration.ComplexType(mockType2);

            var typeMapper = new TypeMapper(new MappingContext(modelConfiguration, new ConventionsConfiguration(), model));

            Assert.NotNull(typeMapper.MapComplexType(mockType1));

            Assert.Equal(
                Strings.SimpleNameCollision("Foo", "Foo", "Foo"),
                Assert.Throws <NotSupportedException>(() => typeMapper.MapComplexType(mockType2)).Message);
        }
コード例 #14
0
        public void HasInverseNavigationProperty_throws_on_incompatible_multiplicity()
        {
            var navigationProperty       = typeof(LightweighEntity).GetDeclaredProperty("ValidNavigationProperty");
            var configuration            = new NavigationPropertyConfiguration(navigationProperty);
            var modelConfiguration       = new ModelConfiguration();
            var lightweightConfiguration = new ConventionNavigationPropertyConfiguration(configuration, modelConfiguration);

            var inverseNavigationProperty =
                typeof(LightweighEntity).GetDeclaredProperty("ValidInverseNavigationProperty");

            lightweightConfiguration.HasInverseEndMultiplicity(RelationshipMultiplicity.Many);

            Assert.Equal(
                Strings.LightweightNavigationPropertyConfiguration_IncompatibleMultiplicity(
                    "*",
                    typeof(LightweighEntity).Name + "." + "ValidInverseNavigationProperty",
                    typeof(LightweighEntity).FullName),
                Assert.Throws <InvalidOperationException>(
                    () => lightweightConfiguration.HasInverseNavigationProperty(p => inverseNavigationProperty)).Message);
        }
コード例 #15
0
        private static void LogMessage(string message, ModelConfiguration partitionedModel)
        {
            //Can provide custom logger here
            try
            {
                if (UseDatabase)
                {
                    ConfigDatabaseHelper.LogMessage(message, partitionedModel);
                }

                Console.WriteLine(message);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
                Environment.Exit(0); //Avoid recursion if errored connecting to db
            }
        }
コード例 #16
0
        public void Map_should_set_clr_property_info_on_assocation_source_end()
        {
            var modelConfiguration = new ModelConfiguration();
            var model      = new EdmModel().Initialize();
            var entityType = new EntityType();

            model.AddEntitySet("Source", entityType);
            var mappingContext = new MappingContext(modelConfiguration, new ConventionsConfiguration(), model);

            var mockPropertyInfo = new MockPropertyInfo(new MockType("Target"), "Nav");

            new NavigationPropertyMapper(new TypeMapper(mappingContext))
            .Map(
                mockPropertyInfo, entityType,
                () => new EntityTypeConfiguration(typeof(object)));

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

            Assert.Same(mockPropertyInfo.Object, associationType.SourceEnd.GetClrPropertyInfo());
        }
コード例 #17
0
        public void Apply_ignores_constraint_when_already_specified()
        {
            var propertyInfo       = typeof(BType3).GetInstanceProperty("A");
            var modelConfiguration = new ModelConfiguration();
            var navigationPropertyConfiguration
                = modelConfiguration.Entity(typeof(BType3)).Navigation(propertyInfo);

            navigationPropertyConfiguration.Constraint
                = new ForeignKeyConstraintConfiguration(new[] { typeof(BType3).GetInstanceProperty("AId1") });

            new ForeignKeyPrimitivePropertyAttributeConvention()
            .Apply(
                typeof(BType3).GetInstanceProperty("AId2"),
                new ConventionTypeConfiguration(typeof(BType3), () => modelConfiguration.Entity(typeof(BType3)), modelConfiguration),
                new ForeignKeyAttribute("A"));

            var foreignKeyConstraint = (ForeignKeyConstraintConfiguration)navigationPropertyConfiguration.Constraint;

            Assert.Equal(new[] { typeof(BType3).GetInstanceProperty("AId1") }, foreignKeyConstraint.ToProperties);
        }
コード例 #18
0
        private void AddSyntheticMembers(
            EntityType entityType,
            ModelConfiguration modelConfiguration)
        {
            foreach (var memberConfiguration in modelConfiguration.SyntheticMembers.Values.Where(o => o.Added))
            {
                var dataProperty = CreateDataProperty(
                    memberConfiguration.MemberName,
                    _dataTypeProvider.GetDataType(memberConfiguration.MemberType),
                    false,
                    IsNullable(memberConfiguration.MemberType),
                    false,
                    memberConfiguration,
                    entityType,
                    null);

                dataProperty.IsUnmapped = true;
                entityType.DataProperties.Add(dataProperty);
            }
        }
コード例 #19
0
        public void Configure_should_configure_default_schema()
        {
            var modelConfiguration
                = new ModelConfiguration
                      {
                          DefaultSchema = "foo"
                      };

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

            Assert.Equal("dbo", databaseMapping.Database.Schemas.Single().Name);
            Assert.Equal("dbo", databaseMapping.Database.Schemas.Single().DatabaseIdentifier);

            modelConfiguration.Configure(databaseMapping, ProviderRegistry.Sql2008_ProviderManifest);

            Assert.Equal("foo", databaseMapping.Database.Schemas.Single().Name);
            Assert.Equal("foo", databaseMapping.Database.Schemas.Single().DatabaseIdentifier);
        }
        public void Apply_ignores_inverse_when_already_configured()
        {
            var mockTypeA = new MockType("A");
            var mockTypeB = new MockType("B").Property(mockTypeA, "A1").Property(mockTypeA, "A2");

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

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

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

            Assert.NotSame(mockTypeB.GetProperty("A1"), navigationPropertyConfiguration.InverseNavigationProperty);
        }
コード例 #21
0
        public virtual string WriteCode(
            [NotNull] ModelConfiguration modelConfiguration)
        {
            Check.NotNull(modelConfiguration, nameof(modelConfiguration));

            _model = modelConfiguration;
            _sb    = new IndentedStringBuilder();

            _sb.AppendLine("using Microsoft.Data.Entity;");
            _sb.AppendLine("using Microsoft.Data.Entity.Metadata;");
            _sb.AppendLine();
            _sb.AppendLine("namespace " + _model.Namespace());
            _sb.AppendLine("{");
            using (_sb.Indent())
            {
                AddClass();
            }
            _sb.Append("}");

            return(_sb.ToString());
        }
コード例 #22
0
        public void Map_should_set_default_association_multiplicity_to_collection_to_optional()
        {
            var modelConfiguration = new ModelConfiguration();
            var model      = new EdmModel(DataSpace.CSpace);
            var entityType = new EntityType("E", "N", DataSpace.CSpace);

            model.AddEntitySet("Source", entityType);
            var mappingContext = new MappingContext(modelConfiguration, new ConventionsConfiguration(), model);

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

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

            var associationType = model.AssociationTypes.Single();

            Assert.Equal(RelationshipMultiplicity.Many, associationType.SourceEnd.RelationshipMultiplicity);
            Assert.Equal(RelationshipMultiplicity.ZeroOrOne, associationType.TargetEnd.RelationshipMultiplicity);
        }
コード例 #23
0
        public void Apply_ignores_constraint_when_already_specified()
        {
            var mockTypeA = new MockType("A");
            var mockTypeB = new MockType("B").Property <int>("AId1").Property <int>("AId2");

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

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

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

            var foreignKeyConstraint = (ForeignKeyConstraintConfiguration)navigationPropertyConfiguration.Constraint;

            Assert.Equal(new[] { mockTypeB.GetProperty("AId1") }, foreignKeyConstraint.ToProperties);
        }
コード例 #24
0
        public void Map_should_detect_collection_associations_and_set_correct_end_kinds()
        {
            var modelConfiguration = new ModelConfiguration();
            var model      = new EdmModel().Initialize();
            var entityType = new EntityType();

            model.AddEntitySet("Source", entityType);
            var mappingContext = new MappingContext(modelConfiguration, new ConventionsConfiguration(), model);

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

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

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

            Assert.Equal(RelationshipMultiplicity.ZeroOrOne, associationType.SourceEnd.RelationshipMultiplicity);
            Assert.Equal(RelationshipMultiplicity.Many, associationType.TargetEnd.RelationshipMultiplicity);
        }
コード例 #25
0
            public void Invokes_action_with_value_when_not_null()
            {
                var    actionInvoked = false;
                object capturedValue = null;
                var    value         = new object();
                var    convention    = new TypeConventionWithHaving <object, object>(
                    Enumerable.Empty <Func <Type, bool> >(),
                    t => value,
                    (c, v) =>
                {
                    actionInvoked = true;
                    capturedValue = v;
                });
                var type          = typeof(object);
                var configuration = new ModelConfiguration();

                convention.Apply(type, configuration);

                Assert.True(actionInvoked);
                Assert.Same(value, capturedValue);
            }
コード例 #26
0
        private void ApplyModelConfiguration(
            Type type,
            JsonPropertyCollection properties,
            ModelConfiguration modelConfiguration,
            ModelMetadata metadata,
            Dictionary <JsonProperty, MemberInfo> propertyMembers)
        {
            foreach (var property in properties)
            {
                var memberConfiguration = modelConfiguration.GetMember(property.UnderlyingName);
                if (memberConfiguration != null)
                {
                    ConfigureProperty(property, memberConfiguration);
                }

                var isMappedProperty       = metadata?.AllProperties.Contains(property.UnderlyingName);
                var syntheticConfiguration = modelConfiguration.GetSyntheticMember(property.UnderlyingName);
                if (syntheticConfiguration == null &&
                    isMappedProperty == false &&
                    memberConfiguration?.Serialize != true &&
                    memberConfiguration?.Deserialize != true)
                {
                    // Do not serialize a non mapped entity property by default (we do not want to expose data that the client will not use)
                    property.Ignored = memberConfiguration?.Ignored ?? true;
                }

                if (syntheticConfiguration?.SerializeFunction != null ||
                    memberConfiguration?.SerializeFunction != null ||
                    propertyMembers.TryGetValue(property, out var member) && member.IsProperty() && !member.IsAutoProperty(true))
                {
                    // Throw when a non auto or synthetic property lazy loads an uninitialized association (e.g. CustomerId => Organization.Customer.Id)
                    property.ValueProvider = CreateLazyLoadGuard(property.ValueProvider, type, property.UnderlyingName);
                }

                if (isMappedProperty == true)
                {
                    property.Writable = memberConfiguration?.Deserialize ?? true; // Non public mapped property setter shall be writable by default
                }
            }
        }
コード例 #27
0
        public DynamicReportDefinition(ModelConfiguration modelConfiguration)
        {
            var entity     = modelConfiguration.ForEntityType <T>();
            var properties = typeof(T).GetProperties();

            foreach (var property in properties)
            {
                if (property.PropertyType.IsValueType || property.PropertyType == typeof(string))
                {
                    var        param            = Expression.Parameter(typeof(T), "_");
                    Expression propertyAccessor = Expression.PropertyOrField(param, property.Name);
                    var        lambda           = Expression.Lambda <Func <T, object> >(Expression.Convert(propertyAccessor, typeof(object)), param);
                    AddCustomField(property.Name, lambda);
                }
                //var field = Fields.Last();
                //var propertyConfig = entity.PropertyMetadata(property.Name);
                //if (propertyConfig != null)
                //{

                //}
            }
        }
コード例 #28
0
        public void Apply_adds_fk_column_when_nav_prop_is_valid()
        {
            var mockTypeA                  = new MockType("A");
            var mockTypeB                  = new MockType("B").Property <int>("AId").Property(mockTypeA, "A");
            var mockPropertyInfo           = mockTypeB.GetProperty("AId");
            var mockNavigationPropertyInfo = mockTypeB.GetProperty("A");

            var modelConfiguration = new ModelConfiguration();

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

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

            Assert.NotNull(navigationPropertyConfiguration.Constraint);

            var foreignKeyConstraint = (ForeignKeyConstraintConfiguration)navigationPropertyConfiguration.Constraint;

            Assert.Equal(new[] { mockTypeB.GetProperty("AId") }, foreignKeyConstraint.ToProperties);
            Assert.Null(navigationPropertyConfiguration.InverseNavigationProperty);
        }
コード例 #29
0
        public void Map_should_create_navigation_property_for_association()
        {
            var modelConfiguration = new ModelConfiguration();
            var model      = new EdmModel().Initialize();
            var entityType = new EntityType();

            model.AddEntitySet("Source", entityType);
            var mappingContext = new MappingContext(modelConfiguration, new ConventionsConfiguration(), model);

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

            Assert.Equal(1, entityType.DeclaredNavigationProperties.Count);

            var navigationProperty = entityType.NavigationProperties.Single();

            Assert.Equal("Nav", navigationProperty.Name);
            Assert.NotNull(navigationProperty.Association);
            Assert.NotSame(entityType, navigationProperty.ResultEnd.GetEntityType());
        }
コード例 #30
0
        public void MapEnumType_should_set_namespace_when_provided_via_model_configuration()
        {
            var model    = new EdmModel(DataSpace.CSpace);
            var mockType = new MockType("Foo");

            mockType.SetupGet(t => t.IsEnum).Returns(true);
            mockType.Setup(t => t.GetEnumUnderlyingType()).Returns(typeof(int));
            mockType.Setup(t => t.GetEnumNames()).Returns(new string[] { });
            mockType.Setup(t => t.GetEnumValues()).Returns(new int[] { });

            var modelConfiguration = new ModelConfiguration
            {
                ModelNamespace = "Bar"
            };

            var typeMapper = new TypeMapper(new MappingContext(modelConfiguration, new ConventionsConfiguration(), model));

            var enumType = typeMapper.MapEnumType(mockType);

            Assert.NotNull(enumType);
            Assert.Equal("Bar", enumType.NamespaceName);
        }
コード例 #31
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public virtual string WriteCode(
            [NotNull] ModelConfiguration modelConfiguration)
        {
            Check.NotNull(modelConfiguration, nameof(modelConfiguration));

            _model = modelConfiguration;
            _sb    = new IndentedStringBuilder();

            _sb.AppendLine("using System;"); // Guid default values require new Guid() which requires this using
            _sb.AppendLine("using Microsoft.EntityFrameworkCore;");
            _sb.AppendLine("using Microsoft.EntityFrameworkCore.Metadata;");
            _sb.AppendLine();
            _sb.AppendLine("namespace " + _model.Namespace());
            _sb.AppendLine("{");
            using (_sb.Indent())
            {
                AddClass();
            }
            _sb.Append("}");

            return(_sb.ToString());
        }
コード例 #32
0
        public override string WriteCode(ModelConfiguration modelConfiguration)
        {
            // There is no good way to override the DbSet naming, as it uses
            // an internal StringBuilder. This means we can't override
            // AddDbSetProperties without re-implementing the entire class.
            // Therefore, we have to get the code and then do string manipulation
            // to replace the DbSet property code

            var code = base.WriteCode(modelConfiguration);

            foreach (var entityConfig in modelConfiguration.EntityConfigurations)
            {
                var entityName = entityConfig.EntityType.Name;
                var setName    = Inflector.Pluralize(entityName) ?? entityName;

                code = code.Replace(
                    $"DbSet<{entityName}> {entityName}",
                    $"DbSet<{entityName}> {setName}");
            }

            return(code);
        }
コード例 #33
0
        bool ValidateUploadedConfig(ModelConfiguration config)
        {
            throw new Lpp.Utilities.CodeToBeUpdatedException();

            //if (config == null)
            //{
            //    ModelState.AddModelError("", "The file appears to be malformed or empty");
            //    return false;
            //}

            //if (config.Id == Guid.Empty)
            //    ModelState.AddModelError("Id", "Id appears to be malformed or empty");

            //if (config.ModelProcessorId == Guid.Empty)
            //    ModelState.AddModelError("ModelProcessorId", "ModelProcessorId appears to be malformed or empty");

            //if (Models.Find(config.Id) != null)
            //    ModelState.AddModelError("Id", "There is already a model registsred with Id = " + config.Id);

            //if (string.IsNullOrEmpty(config.Name))
            //    ModelState.AddModelError("Name", "Name must be defined");

            //ValidateRSAKey(config.PublicKey);

            //if (string.IsNullOrEmpty(config.Version))
            //    ModelState.AddModelError("Version", "Version is not defined");

            //if (config.RequestTypes == null || config.RequestTypes.Length == 0)
            //    ModelState.AddModelError("Request", "No requests are defined for the model. At least one request is required.");

            //int reqNum = 1;
            //foreach (var r in config.RequestTypes.EmptyIfNull())
            //{
            //    ValidateRequestType(r, reqNum++);
            //}

            //return ModelState.IsValid;
        }
コード例 #34
0
        public void Apply_adds_fk_column_when_nav_prop_is_valid()
        {
            var propertyInfo           = typeof(BType2).GetInstanceProperty("AId");
            var navigationPropertyInfo = typeof(BType2).GetInstanceProperty("A");

            var modelConfiguration = new ModelConfiguration();

            new ForeignKeyPrimitivePropertyAttributeConvention()
            .Apply(
                propertyInfo,
                new ConventionTypeConfiguration(typeof(BType2), () => modelConfiguration.Entity(typeof(BType2)), modelConfiguration),
                new ForeignKeyAttribute("A"));

            var navigationPropertyConfiguration
                = modelConfiguration.Entity(typeof(BType2)).Navigation(navigationPropertyInfo);

            Assert.NotNull(navigationPropertyConfiguration.Constraint);

            var foreignKeyConstraint = (ForeignKeyConstraintConfiguration)navigationPropertyConfiguration.Constraint;

            Assert.Equal(new[] { typeof(BType2).GetInstanceProperty("AId") }, foreignKeyConstraint.ToProperties);
            Assert.Null(navigationPropertyConfiguration.InverseNavigationProperty);
        }
コード例 #35
0
        public void Map_should_create_association_sets_for_associations()
        {
            var modelConfiguration = new ModelConfiguration();
            var model      = new EdmModel(DataSpace.CSpace);
            var entityType = new EntityType("Source", "N", DataSpace.CSpace);

            model.AddEntitySet("Source", entityType);

            var mappingContext = new MappingContext(modelConfiguration, new ConventionsConfiguration(), model);

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

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

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

            Assert.NotNull(associationSet);
            Assert.NotNull(associationSet.ElementType);
            Assert.Equal("Source_Nav", associationSet.Name);
        }
コード例 #36
0
        public void Configure_should_configure_active_entities_and_complex_types()
        {
            var mockEntityType = new MockType();
            var mockComplexType = new MockType();

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

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

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

            modelConfiguration.Configure(model);

            mockComplexTypeConfiguration.Verify(c => c.Configure(complexType));
            mockEntityTypeConfiguration.Verify(c => c.Configure(entityType, model));
        }
コード例 #37
0
        public void Map_should_set_namespace_when_provided_via_model_configuration()
        {
            var modelConfiguration
                = new ModelConfiguration
                {
                ModelNamespace = "Foo"
                };
            var model      = new EdmModel(DataSpace.CSpace);
            var entityType = new EntityType("E", "N", DataSpace.CSpace);

            model.AddEntitySet("Source", entityType);
            var mappingContext = new MappingContext(modelConfiguration, new ConventionsConfiguration(), model);

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

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

            var associationType = model.AssociationTypes.Single();

            Assert.Equal("Foo", associationType.NamespaceName);
        }
コード例 #38
0
        private async Task ProcessRefreshPlanAsync(ModelConfiguration model, RefreshPlan refreshPlan,
                                                   CancellationToken cancellationToken)
        {
            try
            {
                using (var server = await GetServerAsync())
                {
                    try
                    {
                        var database = GetDatabase(server, model.DatabaseName);

                        await _dataSourceFactory.Create(model.DataSource.Type)
                        .ProcessAsync(database, model, cancellationToken);

                        Logger.Info($"Processing table {refreshPlan.Table}.");

                        var table = GetTable(database, refreshPlan.Table);
                        refreshPlan.Refresh.Refresh(table);

                        Logger.Info($"Saving {refreshPlan.Table}.");
                        database.Model.SaveChanges(new SaveOptions {
                            MaxParallelism = model.MaxParallelism
                        });
                    }
                    finally
                    {
                        server.Disconnect();
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error(e);
                throw;
            }
        }
コード例 #39
0
        public override Task <ReverseEngineerFiles> WriteCodeAsync(
            [NotNull] ModelConfiguration modelConfiguration,
            [NotNull] string outputPath,
            [NotNull] string dbContextClassName,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            Check.NotNull(modelConfiguration, nameof(modelConfiguration));
            Check.NotEmpty(outputPath, nameof(outputPath));
            Check.NotEmpty(dbContextClassName, nameof(dbContextClassName));

            cancellationToken.ThrowIfCancellationRequested();

            var resultingFiles = new ReverseEngineerFiles();

            var generatedCode = DbContextWriter.WriteCode(modelConfiguration);

            // output DbContext .cs file
            var dbContextFileName     = dbContextClassName + FileExtension;
            var dbContextFileFullPath = FileService.OutputFile(
                outputPath, dbContextFileName, generatedCode);

            resultingFiles.ContextFile = dbContextFileFullPath;

            foreach (var entityConfig in modelConfiguration.EntityConfigurations)
            {
                generatedCode = EntityTypeWriter.WriteCode(entityConfig);

                // output EntityType poco .cs file
                var entityTypeFileName     = entityConfig.EntityType.DisplayName() + FileExtension;
                var entityTypeFileFullPath = FileService.OutputFile(
                    outputPath, entityTypeFileName, generatedCode);
                resultingFiles.EntityTypeFiles.Add(entityTypeFileFullPath);
            }

            return(Task.FromResult(resultingFiles));
        }
コード例 #40
0
        public void MapComplexType_should_throw_for_new_type_if_enum_type_with_same_simple_name_already_used()
        {
            var model = new EdmModel(DataSpace.CSpace);

            var mockType1 = new MockType("Foo");
            var mockType2 = new MockType("Foo");

            var modelConfiguration = new ModelConfiguration();

            modelConfiguration.ComplexType(mockType2);

            mockType1.SetupGet(t => t.IsEnum).Returns(true);
            mockType1.Setup(t => t.GetEnumUnderlyingType()).Returns(typeof(int));
            mockType1.Setup(t => t.GetEnumNames()).Returns(new string[] { });
            mockType1.Setup(t => t.GetEnumValues()).Returns(new int[] { });

            var typeMapper = new TypeMapper(new MappingContext(modelConfiguration, new ConventionsConfiguration(), model));

            Assert.NotNull(typeMapper.MapEnumType(mockType1));

            Assert.Equal(
                Strings.SimpleNameCollision("Foo", "Foo", "Foo"),
                Assert.Throws <NotSupportedException>(() => typeMapper.MapComplexType(mockType2)).Message);
        }
コード例 #41
0
        public void Configure_mapping_can_process_one_level_TPH_on_both_sides_of_tree()
        {
            //Setup
            var model = TestModelBuilderHelpers.CreateSingleLevelInheritanceWithThreeEntities();
            var databaseMapping = new DatabaseMappingGenerator(ProviderRegistry.Sql2008_ProviderManifest).Generate(model);

            var entityType1 = model.GetEntityType("E1");
            var entityType2 = model.GetEntityType("E2");
            var entityType3 = model.GetEntityType("E3");

            // Action
            var modelConfiguration = new ModelConfiguration();
            var entity1Configuration = modelConfiguration.Entity(entityType1.GetClrType());
            var entity1MappingConfiguration =
                new EntityMappingConfiguration
                    {
                        TableName = new DatabaseName("E1")
                    };
            entity1MappingConfiguration
                .AddValueCondition(
                    new ValueConditionConfiguration(entity1MappingConfiguration, "P3")
                        {
                            Value = null
                        });
            entity1MappingConfiguration
                .AddValueCondition(
                    new ValueConditionConfiguration(entity1MappingConfiguration, "P4")
                        {
                            Value = null
                        });
            entity1Configuration.AddMappingConfiguration(entity1MappingConfiguration);
            var entity1SubTypeMappingConfiguration =
                new EntityMappingConfiguration
                    {
                        TableName = new DatabaseName("E1")
                    };
            entity1SubTypeMappingConfiguration
                .AddValueCondition(
                    new ValueConditionConfiguration(entity1SubTypeMappingConfiguration, "P3")
                        {
                            Value = null
                        });
            entity1SubTypeMappingConfiguration
                .AddNullabilityCondition(
                    new NotNullConditionConfiguration(
                        entity1SubTypeMappingConfiguration,
                        new PropertyPath(entityType3.GetDeclaredPrimitiveProperty("P4").GetClrPropertyInfo())));
            entity1Configuration.AddSubTypeMappingConfiguration(entityType3.GetClrType(), entity1SubTypeMappingConfiguration);
            var entity2Configuration = modelConfiguration.Entity(entityType2.GetClrType());
            var entity2MappingConfiguration =
                new EntityMappingConfiguration
                    {
                        TableName = new DatabaseName("E1")
                    };
            entity2MappingConfiguration
                .AddNullabilityCondition(
                    new NotNullConditionConfiguration(
                        entity2MappingConfiguration, new PropertyPath(entityType2.GetDeclaredPrimitiveProperty("P3").GetClrPropertyInfo())));
            entity2MappingConfiguration
                .AddValueCondition(
                    new ValueConditionConfiguration(entity2MappingConfiguration, "P4")
                        {
                            Value = null
                        });
            entity2Configuration.AddMappingConfiguration(entity2MappingConfiguration);
            modelConfiguration.NormalizeConfigurations();
            modelConfiguration.Configure(databaseMapping, ProviderRegistry.Sql2008_ProviderManifest);

            //Validate
            var entitySetMapping = databaseMapping.GetEntitySetMapping(model.GetEntitySet(entityType1));
            Assert.NotNull(entitySetMapping);
            Assert.Equal(4, entitySetMapping.EntityTypeMappings.Count);

            var entityType1Mapping = databaseMapping.GetEntityTypeMapping(entityType1);
            var entityType1MappingConditions = databaseMapping.GetEntityTypeMappings(entityType1).Single(x => !x.IsHierarchyMapping);
            var entityType2Mapping = databaseMapping.GetEntityTypeMapping(entityType2);
            var entityType3Mapping = databaseMapping.GetEntityTypeMapping(entityType3);

            var table1 = entityType1Mapping.TypeMappingFragments.Single().Table;
            var table2 = entityType2Mapping.TypeMappingFragments.Single().Table;
            var table3 = entityType3Mapping.TypeMappingFragments.Single().Table;

            Assert.True(entityType1Mapping.IsHierarchyMapping);
            Assert.Equal(4, table1.Columns.Count);
            Assert.Equal("P1", table1.Columns[0].Name);
            Assert.Equal("P2", table1.Columns[1].Name);
            Assert.Equal("P3", table1.Columns[2].Name);
            Assert.Equal("P4", table1.Columns[3].Name);
            Assert.Equal(2, entityType1Mapping.TypeMappingFragments.Single().PropertyMappings.Count);
            Assert.Equal("P1", entityType1Mapping.TypeMappingFragments.Single().PropertyMappings[0].Column.Name);
            Assert.Equal("P2", entityType1Mapping.TypeMappingFragments.Single().PropertyMappings[1].Column.Name);
            Assert.Same(table1.Columns[2], entityType1MappingConditions.TypeMappingFragments.Single().ColumnConditions[0].Column);
            Assert.True((bool)entityType1MappingConditions.TypeMappingFragments.Single().ColumnConditions[0].IsNull);
            Assert.Same(table1.Columns[3], entityType1MappingConditions.TypeMappingFragments.Single().ColumnConditions[1].Column);
            Assert.True((bool)entityType1MappingConditions.TypeMappingFragments.Single().ColumnConditions[1].IsNull);

            Assert.False(entityType2Mapping.IsHierarchyMapping);
            Assert.Same(table1, table2);
            Assert.Same(table1.Columns[0], table2.Columns[0]);
            Assert.Same(table1.Columns[1], table2.Columns[1]);
            Assert.Equal(2, entityType2Mapping.TypeMappingFragments.Single().PropertyMappings.Count);
            Assert.Equal("P1", entityType2Mapping.TypeMappingFragments.Single().PropertyMappings[0].Column.Name);
            Assert.Equal("P3", entityType2Mapping.TypeMappingFragments.Single().PropertyMappings[1].Column.Name);
            Assert.Same(table1.Columns[3], entityType2Mapping.TypeMappingFragments.Single().ColumnConditions[0].Column);
            Assert.True((bool)entityType2Mapping.TypeMappingFragments.Single().ColumnConditions[0].IsNull);
            Assert.Same(table1.Columns[2], entityType2Mapping.TypeMappingFragments.Single().ColumnConditions[1].Column);
            Assert.False((bool)entityType2Mapping.TypeMappingFragments.Single().ColumnConditions[1].IsNull);

            Assert.False(entityType3Mapping.IsHierarchyMapping);
            Assert.Same(table1, table3);
            Assert.Same(table1.Columns[0], table3.Columns[0]);
            Assert.Same(table1.Columns[1], table3.Columns[1]);
            Assert.Equal(2, entityType3Mapping.TypeMappingFragments.Single().PropertyMappings.Count);
            Assert.Equal("P1", entityType3Mapping.TypeMappingFragments.Single().PropertyMappings[0].Column.Name);
            Assert.Equal("P4", entityType3Mapping.TypeMappingFragments.Single().PropertyMappings[1].Column.Name);
            Assert.Same(table1.Columns[2], entityType3Mapping.TypeMappingFragments.Single().ColumnConditions[0].Column);
            Assert.True((bool)entityType3Mapping.TypeMappingFragments.Single().ColumnConditions[0].IsNull);
            Assert.Same(table1.Columns[3], entityType3Mapping.TypeMappingFragments.Single().ColumnConditions[1].Column);
            Assert.False((bool)entityType3Mapping.TypeMappingFragments.Single().ColumnConditions[1].IsNull);
        }
コード例 #42
0
        public void Configure_mapping_can_process_simple_TPH_mapping()
        {
            //Setup
            var model = TestModelBuilderHelpers.CreateSimpleInheritanceTwoEntities();
            var databaseMapping = new DatabaseMappingGenerator(ProviderRegistry.Sql2008_ProviderManifest).Generate(model);

            var entityType1 = model.GetEntityType("E1");
            var entityType2 = model.GetEntityType("E2");

            // Action
            var modelConfiguration = new ModelConfiguration();
            var entity1Configuration = modelConfiguration.Entity(entityType1.GetClrType());
            var entity1MappingConfiguration =
                new EntityMappingConfiguration
                    {
                        TableName = new DatabaseName("E1")
                    };
            entity1MappingConfiguration
                .AddValueCondition(
                    new ValueConditionConfiguration(entity1MappingConfiguration, "disc")
                        {
                            Value = "foo"
                        });
            entity1Configuration.AddMappingConfiguration(entity1MappingConfiguration);
            var entity1SubTypeMappingConfiguration =
                new EntityMappingConfiguration
                    {
                        TableName = new DatabaseName("E1")
                    };
            entity1SubTypeMappingConfiguration
                .AddValueCondition(
                    new ValueConditionConfiguration(entity1SubTypeMappingConfiguration, "disc")
                        {
                            Value = "bar"
                        });
            entity1Configuration.AddSubTypeMappingConfiguration(entityType2.GetClrType(), entity1SubTypeMappingConfiguration);
            modelConfiguration.NormalizeConfigurations();
            modelConfiguration.Configure(databaseMapping, ProviderRegistry.Sql2008_ProviderManifest);

            //Validate
            var entitySetMapping = databaseMapping.GetEntitySetMapping(model.GetEntitySet(entityType1));
            Assert.NotNull(entitySetMapping);
            Assert.Equal(3, entitySetMapping.EntityTypeMappings.Count);
            var entityType1Mapping = databaseMapping.GetEntityTypeMapping(entityType1);
            var entityType1MappingConditions = databaseMapping.GetEntityTypeMappings(entityType1).Single(tm => !tm.IsHierarchyMapping);
            var entityType2Mapping = databaseMapping.GetEntityTypeMapping(entityType2);

            var table1 = entityType1Mapping.TypeMappingFragments.Single().Table;
            var table2 = entityType2Mapping.TypeMappingFragments.Single().Table;

            Assert.True(entityType1Mapping.IsHierarchyMapping);
            Assert.Equal(4, table1.Columns.Count);
            Assert.Equal("P1", table1.Columns[0].Name);
            Assert.Equal("P2", table1.Columns[1].Name);
            Assert.Equal("P3", table1.Columns[2].Name);
            Assert.Equal("disc", table1.Columns[3].Name);
            Assert.Equal(2, entityType1Mapping.TypeMappingFragments.Single().PropertyMappings.Count);
            Assert.Equal("P1", entityType1Mapping.TypeMappingFragments.Single().PropertyMappings[0].Column.Name);
            Assert.Equal("P2", entityType1Mapping.TypeMappingFragments.Single().PropertyMappings[1].Column.Name);
            Assert.Same(table1.Columns[3], entityType1MappingConditions.TypeMappingFragments.Single().ColumnConditions.Single().Column);
            Assert.Equal("foo", entityType1MappingConditions.TypeMappingFragments.Single().ColumnConditions.Single().Value);
            Assert.Equal("nvarchar", entityType1MappingConditions.TypeMappingFragments.Single().ColumnConditions.Single().Column.TypeName);
            Assert.Equal(
                DatabaseMappingGenerator.DiscriminatorLength,
                entityType1MappingConditions.TypeMappingFragments.Single().ColumnConditions.Single().Column.Facets.MaxLength);

            Assert.False(entityType2Mapping.IsHierarchyMapping);
            Assert.Same(table1, table2);
            Assert.Equal(2, entityType2Mapping.TypeMappingFragments.Single().PropertyMappings.Count);
            Assert.Same(table1.Columns[0], table2.Columns[0]);
            Assert.Same(table1.Columns[1], table2.Columns[1]);
            Assert.Equal("P1", entityType2Mapping.TypeMappingFragments.Single().PropertyMappings[0].Column.Name);
            Assert.Equal("P3", entityType2Mapping.TypeMappingFragments.Single().PropertyMappings[1].Column.Name);
            Assert.Same(table2.Columns[3], entityType2Mapping.TypeMappingFragments.Single().ColumnConditions.Single().Column);
            Assert.Equal("bar", entityType2Mapping.TypeMappingFragments.Single().ColumnConditions.Single().Value);
        }
コード例 #43
0
        public void Configure_mapping_can_process_one_level_TPC_on_both_sides_of_tree()
        {
            //Setup
            var model = TestModelBuilderHelpers.CreateSingleLevelInheritanceWithThreeEntities();
            var databaseMapping = new DatabaseMappingGenerator(ProviderRegistry.Sql2008_ProviderManifest).Generate(model);

            var entityType1 = model.GetEntityType("E1");
            var entityType2 = model.GetEntityType("E2");
            var entityType3 = model.GetEntityType("E3");

            // Action
            var modelConfiguration = new ModelConfiguration();
            modelConfiguration.Entity(entityType2.GetClrType())
                .AddMappingConfiguration(
                    new EntityMappingConfiguration
                        {
                            MapInheritedProperties = true,
                            TableName = new DatabaseName("E2")
                        });
            modelConfiguration.Entity(entityType3.GetClrType())
                .AddMappingConfiguration(
                    new EntityMappingConfiguration
                        {
                            MapInheritedProperties = true,
                            TableName = new DatabaseName("E3")
                        });
            modelConfiguration.Configure(databaseMapping, ProviderRegistry.Sql2008_ProviderManifest);

            //Validate
            var entitySetMapping = databaseMapping.GetEntitySetMapping(model.GetEntitySet(entityType1));
            Assert.NotNull(entitySetMapping);
            Assert.Equal(3, entitySetMapping.EntityTypeMappings.Count);

            var entityType1Mapping = databaseMapping.GetEntityTypeMapping(entityType1);
            var entityType2Mapping = databaseMapping.GetEntityTypeMapping(entityType2);
            var entityType3Mapping = databaseMapping.GetEntityTypeMapping(entityType3);

            var table1 = entityType1Mapping.TypeMappingFragments.Single().Table;
            var table2 = entityType2Mapping.TypeMappingFragments.Single().Table;
            var table3 = entityType3Mapping.TypeMappingFragments.Single().Table;

            Assert.False(entityType1Mapping.IsHierarchyMapping);
            Assert.Equal(2, table1.Columns.Count);
            Assert.Equal("P1", table1.Columns[0].Name);
            Assert.Equal("P2", table1.Columns[1].Name);
            Assert.Equal(2, entityType1Mapping.TypeMappingFragments.Single().PropertyMappings.Count);
            Assert.Same(entityType1Mapping.TypeMappingFragments.Single().PropertyMappings[0].Column, table1.Columns[0]);
            Assert.Same(entityType1Mapping.TypeMappingFragments.Single().PropertyMappings[1].Column, table1.Columns[1]);

            Assert.False(entityType2Mapping.IsHierarchyMapping);
            Assert.Equal("E2", table2.Name);
            Assert.Equal(3, table2.Columns.Count);
            Assert.Equal("P1", table2.Columns[0].Name);
            Assert.Equal("P2", table2.Columns[1].Name);
            Assert.Equal("P3", table2.Columns[2].Name);
            Assert.NotSame(table1, table2);
            Assert.NotSame(table1.Columns[0], table2.Columns[0]);
            Assert.NotSame(table1.Columns[1], table2.Columns[1]);
            Assert.Equal(3, entityType2Mapping.TypeMappingFragments.Single().PropertyMappings.Count);
            Assert.Same(entityType2Mapping.TypeMappingFragments.Single().PropertyMappings[0].Column, table2.Columns[0]);
            Assert.Same(entityType2Mapping.TypeMappingFragments.Single().PropertyMappings[1].Column, table2.Columns[1]);
            Assert.Same(entityType2Mapping.TypeMappingFragments.Single().PropertyMappings[2].Column, table2.Columns[2]);

            Assert.False(entityType3Mapping.IsHierarchyMapping);
            Assert.Equal("E3", table3.Name);
            Assert.Equal(3, table3.Columns.Count);
            Assert.Equal("P1", table3.Columns[0].Name);
            Assert.Equal("P2", table3.Columns[1].Name);
            Assert.Equal("P4", table3.Columns[2].Name);
            Assert.NotSame(table1, table3);
            Assert.NotSame(table3, table2);
            Assert.NotSame(table1.Columns[0], table3.Columns[0]);
            Assert.NotSame(table1.Columns[1], table3.Columns[1]);
            Assert.Equal(3, entityType3Mapping.TypeMappingFragments.Single().PropertyMappings.Count);
            Assert.Same(entityType3Mapping.TypeMappingFragments.Single().PropertyMappings[0].Column, table3.Columns[0]);
            Assert.Same(entityType3Mapping.TypeMappingFragments.Single().PropertyMappings[1].Column, table3.Columns[1]);
            Assert.Same(entityType3Mapping.TypeMappingFragments.Single().PropertyMappings[2].Column, table3.Columns[2]);
        }
コード例 #44
0
        public void ComplexType_should_return_new_configuration_if_no_configuration_found()
        {
            var modelConfiguration = new ModelConfiguration();

            Assert.NotNull(modelConfiguration.ComplexType(typeof(object)));
        }
コード例 #45
0
        public void ApplyPropertyConfiguration_should_run_property_model_conventions()
        {
            var mockConvention = new Mock<IConfigurationConvention<PropertyInfo, ModelConfiguration>>();
            var conventionsConfiguration = new ConventionsConfiguration(
                new IConvention[] { mockConvention.Object });
            var mockPropertyInfo = new MockPropertyInfo(typeof(object), "N");
            var modelConfiguration = new ModelConfiguration();

            conventionsConfiguration.ApplyPropertyConfiguration(mockPropertyInfo, modelConfiguration);

            mockConvention.Verify(c => c.Apply(mockPropertyInfo, It.IsAny<Func<ModelConfiguration>>()), Times.AtMostOnce());
        }
コード例 #46
0
        public void Can_add_and_get_entity_configuration()
        {
            var modelConfiguration = new ModelConfiguration();
            var entityTypeConfiguration = new Mock<EntityTypeConfiguration>(typeof(object)).Object;
            modelConfiguration.Add(entityTypeConfiguration);

            Assert.Same(entityTypeConfiguration, modelConfiguration.Entity(typeof(object)));
        }
コード例 #47
0
        public void Adding_complex_type_and_entity_configurations_should_throw()
        {
            var modelConfiguration = new ModelConfiguration();
            var complexTypeConfiguration = new Mock<ComplexTypeConfiguration>(typeof(object)).Object;
            var entityTypeConfiguration = new Mock<EntityTypeConfiguration>(typeof(object)).Object;
            modelConfiguration.Add(complexTypeConfiguration);

            Assert.Equal(
                Strings.DuplicateStructuralTypeConfiguration(typeof(object)),
                Assert.Throws<InvalidOperationException>(() => modelConfiguration.Add(entityTypeConfiguration)).Message);
        }
コード例 #48
0
        public void GetStructuralTypeConfiguration_should_return_registered_complex_type_configuration()
        {
            var modelConfiguration = new ModelConfiguration();
            var complexTypeConfiguration = new Mock<ComplexTypeConfiguration>(typeof(object)).Object;
            modelConfiguration.Add(complexTypeConfiguration);

            Assert.Same(complexTypeConfiguration, modelConfiguration.GetStructuralTypeConfiguration(typeof(object)));
        }
コード例 #49
0
        public void GetStructuralTypeConfiguration_should_return_registered_entity_configuration()
        {
            var modelConfiguration = new ModelConfiguration();
            var entityTypeConfiguration = new Mock<EntityTypeConfiguration>(typeof(object)).Object;
            modelConfiguration.Add(entityTypeConfiguration);

            Assert.Same(entityTypeConfiguration, modelConfiguration.GetStructuralTypeConfiguration(typeof(object)));
        }
コード例 #50
0
        public void ComplexType_should_throw_when_configuration_is_not_for_complex_type()
        {
            var modelConfiguration = new ModelConfiguration();
            modelConfiguration.Add(new Mock<EntityTypeConfiguration>(typeof(object)).Object);

            Assert.Equal(
                Strings.ComplexTypeConfigurationMismatch(typeof(object)),
                Assert.Throws<InvalidOperationException>(() => modelConfiguration.ComplexType(typeof(object))).Message);
        }
コード例 #51
0
        public void Configure_mapping_can_process_entity_splitting()
        {
            EdmModel model =
                new TestModelBuilder()
                    .Entity("E")
                    .Key("P1")
                    .Property("P2")
                    .Property("P3")
                    .Property("P4")
                    .Property("P5");
            var databaseMapping = new DatabaseMappingGenerator(ProviderRegistry.Sql2008_ProviderManifest).Generate(model);

            var entityType = model.GetEntityType("E");
            var modelConfiguration = new ModelConfiguration();
            var entityMappingConfiguration1 =
                new EntityMappingConfiguration
                    {
                        Properties =
                            new List<PropertyPath>
                                {
                                    new PropertyPath(entityType.GetDeclaredPrimitiveProperty("P1").GetClrPropertyInfo()),
                                    new PropertyPath(entityType.GetDeclaredPrimitiveProperty("P2").GetClrPropertyInfo()),
                                    new PropertyPath(entityType.GetDeclaredPrimitiveProperty("P3").GetClrPropertyInfo())
                                },
                        TableName = new DatabaseName("E1")
                    };
            var entityMappingConfiguration2 =
                new EntityMappingConfiguration
                    {
                        Properties =
                            new List<PropertyPath>
                                {
                                    new PropertyPath(entityType.GetDeclaredPrimitiveProperty("P1").GetClrPropertyInfo()),
                                    new PropertyPath(entityType.GetDeclaredPrimitiveProperty("P4").GetClrPropertyInfo()),
                                    new PropertyPath(entityType.GetDeclaredPrimitiveProperty("P5").GetClrPropertyInfo())
                                },
                        TableName = new DatabaseName("E2")
                    };
            var entityConfiguration = modelConfiguration.Entity(entityType.GetClrType());
            entityConfiguration.AddMappingConfiguration(entityMappingConfiguration1);
            entityConfiguration.AddMappingConfiguration(entityMappingConfiguration2);
            modelConfiguration.Configure(databaseMapping, ProviderRegistry.Sql2008_ProviderManifest);

            var entityTypeMapping = databaseMapping.GetEntityTypeMapping(entityType);
            var table1 = entityTypeMapping.TypeMappingFragments[0].Table;
            var table2 = entityTypeMapping.TypeMappingFragments[1].Table;
            Assert.NotSame(table1, table2);
            Assert.Equal("E1", table1.GetTableName().Name);
            Assert.Equal("E2", table2.GetTableName().Name);
            Assert.Equal(3, table1.Columns.Count);
            Assert.Equal(3, table2.Columns.Count);
            Assert.Equal(2, entityTypeMapping.TypeMappingFragments.Count);
            var entityTypeMappingFragment1 = entityTypeMapping.TypeMappingFragments[0];
            var entityTypeMappingFragment2 = entityTypeMapping.TypeMappingFragments[1];
            Assert.Equal(3, entityTypeMappingFragment1.PropertyMappings.Count);
            Assert.Equal("P1", entityTypeMappingFragment1.PropertyMappings[0].Column.Name);
            Assert.Equal("P2", entityTypeMappingFragment1.PropertyMappings[1].Column.Name);
            Assert.Equal("P3", entityTypeMappingFragment1.PropertyMappings[2].Column.Name);
            Assert.Equal(3, entityTypeMappingFragment2.PropertyMappings.Count);
            Assert.Equal("P1", entityTypeMappingFragment2.PropertyMappings[0].Column.Name);
            Assert.Equal("P4", entityTypeMappingFragment2.PropertyMappings[1].Column.Name);
            Assert.Equal("P5", entityTypeMappingFragment2.PropertyMappings[2].Column.Name);
        }
コード例 #52
0
        public void Configure_entity_splitting_should_throw_if_ignored_property_is_mapped()
        {
            EdmModel model =
                new TestModelBuilder()
                    .Entity("E")
                    .Key("P1");
            var databaseMapping = new DatabaseMappingGenerator(ProviderRegistry.Sql2008_ProviderManifest).Generate(model);

            var entityType = model.GetEntityType("E");
            var modelConfiguration = new ModelConfiguration();
            var entityConfiguration = modelConfiguration.Entity(entityType.GetClrType());
            var p1PropertyInfo = entityType.GetDeclaredPrimitiveProperty("P1").GetClrPropertyInfo();
            var entityMappingConfiguration1 =
                new EntityMappingConfiguration
                    {
                        Properties = new List<PropertyPath>
                                         {
                                             new PropertyPath(p1PropertyInfo),
                                             new PropertyPath(new MockPropertyInfo(typeof(int), "P2"))
                                         },
                        TableName = new DatabaseName("E")
                    };
            entityConfiguration.AddMappingConfiguration(entityMappingConfiguration1);

            Assert.Equal(
                Strings.EntityMappingConfiguration_CannotMapIgnoredProperty("E", "P2"),
                Assert.Throws<InvalidOperationException>(
                    () => modelConfiguration.Configure(databaseMapping, ProviderRegistry.Sql2008_ProviderManifest)).Message);
        }
コード例 #53
0
        public void ComplexTypes_returns_only_configured_non_ignored_complex_types()
        {
            var modelConfiguration = new ModelConfiguration();
            modelConfiguration.Entity(new MockType());
            var mockComplexType = new MockType();
            modelConfiguration.ComplexType(mockComplexType);
            var mockIgnoredComplexType = new MockType();
            modelConfiguration.ComplexType(mockIgnoredComplexType);
            modelConfiguration.Ignore(mockIgnoredComplexType);

            Assert.Same(mockComplexType.Object, modelConfiguration.ComplexTypes.Single());
        }
コード例 #54
0
        public void Configure_mapping_can_configure_one_level_TPT_on_both_sides_of_tree()
        {
            //Setup
            var model = TestModelBuilderHelpers.CreateSingleLevelInheritanceWithThreeEntities();

            var entityType1 = model.GetEntityType("E1");
            var entityType2 = model.GetEntityType("E2");
            var entityType3 = model.GetEntityType("E3");
            entityType1.GetDeclaredPrimitiveProperty("P1").SetStoreGeneratedPattern(DbStoreGeneratedPattern.Identity);

            var databaseMapping = new DatabaseMappingGenerator(ProviderRegistry.Sql2008_ProviderManifest).Generate(model);
            var modelConfiguration = new ModelConfiguration();
            modelConfiguration.Entity(entityType2.GetClrType()).ToTable("E2");
            modelConfiguration.Entity(entityType3.GetClrType()).ToTable("E3");

            modelConfiguration.Configure(databaseMapping, ProviderRegistry.Sql2008_ProviderManifest);

            var entityTypeMapping1 = databaseMapping.GetEntityTypeMapping(entityType1);
            var entityTypeMapping2 = databaseMapping.GetEntityTypeMapping(entityType2);
            var entityTypeMapping3 = databaseMapping.GetEntityTypeMapping(entityType3);

            var table1 = entityTypeMapping1.TypeMappingFragments.Single().Table;
            var table2 = entityTypeMapping2.TypeMappingFragments.Single().Table;
            var table3 = entityTypeMapping3.TypeMappingFragments.Single().Table;

            Assert.NotSame(table1, table2);
            Assert.NotSame(table1, table3);
            Assert.NotSame(table3, table2);

            Assert.True(entityTypeMapping1.IsHierarchyMapping);
            Assert.Equal(2, table1.Columns.Count);
            Assert.Equal("P1", table1.Columns[0].Name);
            Assert.Equal(DbStoreGeneratedPattern.Identity, table1.Columns[0].StoreGeneratedPattern);
            Assert.Equal("P2", table1.Columns[1].Name);
            Assert.Equal(2, entityTypeMapping1.TypeMappingFragments.Single().PropertyMappings.Count);
            Assert.Equal("P1", entityTypeMapping1.TypeMappingFragments.Single().PropertyMappings[0].Column.Name);
            Assert.Equal("P2", entityTypeMapping1.TypeMappingFragments.Single().PropertyMappings[1].Column.Name);

            Assert.False(entityTypeMapping2.IsHierarchyMapping);
            Assert.Equal(2, entityTypeMapping2.TypeMappingFragments.Single().PropertyMappings.Count);
            Assert.Equal("P1", entityTypeMapping2.TypeMappingFragments.Single().PropertyMappings[0].Column.Name);
            Assert.Equal(DbStoreGeneratedPattern.None, table2.Columns[0].StoreGeneratedPattern);
            Assert.Equal("P3", entityTypeMapping2.TypeMappingFragments.Single().PropertyMappings[1].Column.Name);
            Assert.Equal(2, table2.Columns.Count);
            Assert.Equal("P1", table2.Columns[0].Name);
            Assert.Equal("P3", table2.Columns[1].Name);
            Assert.NotSame(table1.Columns[0], table2.Columns[0]);

            Assert.False(entityTypeMapping3.IsHierarchyMapping);
            Assert.Equal(2, entityTypeMapping3.TypeMappingFragments.Single().PropertyMappings.Count);
            Assert.Equal(DbStoreGeneratedPattern.None, table3.Columns[0].StoreGeneratedPattern);
            Assert.Equal("P1", entityTypeMapping3.TypeMappingFragments.Single().PropertyMappings[0].Column.Name);
            Assert.Equal("P4", entityTypeMapping3.TypeMappingFragments.Single().PropertyMappings[1].Column.Name);
            Assert.Equal(2, table3.Columns.Count);
            Assert.Equal("P1", table3.Columns[0].Name);
            Assert.Equal("P4", table3.Columns[1].Name);
            Assert.NotSame(table1.Columns[0], table3.Columns[0]);
            Assert.NotSame(table2.Columns[0], table3.Columns[0]);
        }
コード例 #55
0
        public void GetStructuralTypeConfiguration_should_return_null_configuration_when_not_found()
        {
            var modelConfiguration = new ModelConfiguration();

            Assert.Null(modelConfiguration.GetStructuralTypeConfiguration(typeof(object)));
        }
コード例 #56
0
        public void Can_add_and_get_complex_type_configuration()
        {
            var modelConfiguration = new ModelConfiguration();
            var complexTypeConfiguration = new Mock<ComplexTypeConfiguration>(typeof(object)).Object;
            modelConfiguration.Add(complexTypeConfiguration);

            Assert.Same(complexTypeConfiguration, modelConfiguration.ComplexType(typeof(object)));
        }
コード例 #57
0
        public void IsComplexType_should_return_true_when_type_is_complex()
        {
            var modelConfiguration = new ModelConfiguration();
            modelConfiguration.Add(new Mock<ComplexTypeConfiguration>(typeof(object)).Object);

            Assert.True(modelConfiguration.IsComplexType(typeof(object)));
        }
コード例 #58
0
        public void Ignore_should_add_property_to_list_of_ignored_properties()
        {
            var modelConfiguration = new ModelConfiguration();

            modelConfiguration.Ignore(typeof(string));

            Assert.True(modelConfiguration.IsIgnoredType(typeof(string)));
        }
コード例 #59
0
        public void Entity_should_return_new_configuration_if_no_configuration_found()
        {
            var modelConfiguration = new ModelConfiguration();

            Assert.NotNull(modelConfiguration.Entity(typeof(object)));
        }
コード例 #60
0
        public void ConfiguredTypes_returns_all_known_types()
        {
            var modelConfiguration = new ModelConfiguration();
            modelConfiguration.Entity(new MockType());
            modelConfiguration.ComplexType(new MockType());
            modelConfiguration.Ignore(new MockType());

            Assert.Equal(3, modelConfiguration.ConfiguredTypes.Count());
        }