Esempio n. 1
0
        public void Model_differ_breaks_foreign_key_cycles()
        {
            var model = new Entity.Metadata.Model();

            var firstType = model.AddEntityType("First");
            var firstKey  = firstType.SetPrimaryKey(firstType.AddProperty("ID", typeof(int), true));
            var firstFk   = firstType.AddProperty("FK", typeof(int), true);

            var secondType = model.AddEntityType("Second");
            var secondKey  = secondType.SetPrimaryKey(secondType.AddProperty("ID", typeof(int), true));
            var secondFk   = secondType.AddProperty("FK", typeof(int), true);

            firstType.AddForeignKey(firstFk, secondKey);
            secondType.AddForeignKey(secondFk, firstKey);

            var modelDiffer = new ModelDiffer(new RelationalTypeMapper());

            var result = modelDiffer.GetDifferences(null, model);

            Assert.Equal(3, result.Count);

            var firstOperation  = result[0] as CreateTableOperation;
            var secondOperation = result[1] as CreateTableOperation;
            var thirdOperation  = result[2] as AddForeignKeyOperation;

            Assert.NotNull(firstOperation);
            Assert.NotNull(secondOperation);
            Assert.NotNull(thirdOperation);

            Assert.Equal(0, firstOperation.ForeignKeys.Count);
            Assert.Equal(1, secondOperation.ForeignKeys.Count);
            Assert.Equal(firstOperation.Name, thirdOperation.Table);
        }
Esempio n. 2
0
        public void Model_differ_breaks_foreign_key_cycles()
        {
            var model = new Entity.Metadata.Model();

            var firstType = model.AddEntityType("First");
            var firstKey = firstType.SetPrimaryKey(firstType.AddProperty("ID", typeof(int), true));
            var firstFk = firstType.AddProperty("FK", typeof(int), true);

            var secondType = model.AddEntityType("Second");
            var secondKey = secondType.SetPrimaryKey(secondType.AddProperty("ID", typeof(int), true));
            var secondFk = secondType.AddProperty("FK", typeof(int), true);

            firstType.AddForeignKey(firstFk, secondKey);
            secondType.AddForeignKey(secondFk, firstKey);

            var modelDiffer = new ModelDiffer(new RelationalTypeMapper());

            var result = modelDiffer.GetDifferences(null, model);

            Assert.Equal(3, result.Count);

            var firstOperation = result[0] as CreateTableOperation;
            var secondOperation = result[1] as CreateTableOperation;
            var thirdOperation = result[2] as AddForeignKeyOperation;

            Assert.NotNull(firstOperation);
            Assert.NotNull(secondOperation);
            Assert.NotNull(thirdOperation);

            Assert.Equal(0, firstOperation.ForeignKeys.Count);
            Assert.Equal(1, secondOperation.ForeignKeys.Count);
            Assert.Equal(firstOperation.Name, thirdOperation.Table);
        }
Esempio n. 3
0
        public virtual void Does_not_detect_non_instantiable_types()
        {
            var model          = new Entity.Metadata.Model();
            var entityAbstract = model.AddEntityType(typeof(Abstract));
            var entityGeneric  = model.AddEntityType(typeof(Generic <>));

            entityGeneric.BaseType = entityAbstract;

            CreateModelValidator().Validate(model);
        }
Esempio n. 4
0
        public virtual void Detects_missing_discriminator_property()
        {
            var model   = new Entity.Metadata.Model();
            var entityA = model.AddEntityType(typeof(A));
            var entityC = model.AddEntityType(typeof(C));

            entityC.BaseType = entityA;

            VerifyError(Strings.NoDiscriminatorProperty(entityC.DisplayName()), model);
        }
Esempio n. 5
0
        public virtual void Does_not_detects_duplicate_table_names_for_inherited_entities()
        {
            var model   = new Entity.Metadata.Model();
            var entityA = model.AddEntityType(typeof(A));
            var entityC = model.AddEntityType(typeof(C));

            entityC.BaseType = entityA;

            CreateModelValidator().Validate(model);
        }
Esempio n. 6
0
        public virtual void Detects_duplicate_table_names()
        {
            var model   = new Entity.Metadata.Model();
            var entityA = model.AddEntityType(typeof(A));
            var entityB = model.AddEntityType(typeof(B));

            entityA.Relational().TableName = "Table";
            entityB.Relational().TableName = "Table";

            VerifyError(Strings.DuplicateTableName("Table", null, entityB.DisplayName()), model);
        }
Esempio n. 7
0
        public virtual void Detects_duplicate_table_names_with_schema()
        {
            var model   = new Entity.Metadata.Model();
            var entityA = model.AddEntityType(typeof(A));
            var entityB = model.AddEntityType(typeof(B));

            entityA.Relational().Table  = "Table";
            entityA.Relational().Schema = "Schema";
            entityB.Relational().Table  = "Table";
            entityB.Relational().Schema = "Schema";

            VerifyError(Relational.Internal.Strings.DuplicateTableName("Table", "Schema", entityB.DisplayName()), model);
        }
Esempio n. 8
0
        public virtual void Does_not_detect_duplicate_table_names_in_different_schema()
        {
            var model   = new Entity.Metadata.Model();
            var entityA = model.AddEntityType(typeof(A));
            var entityB = model.AddEntityType(typeof(B));

            entityA.Relational().TableName = "Table";
            entityA.Relational().Schema    = "SchemaA";
            entityB.Relational().TableName = "Table";
            entityB.Relational().Schema    = "SchemaB";

            CreateModelValidator().Validate(model);
        }
        public virtual void Detects_missing_discriminator_value_on_leaf()
        {
            var model = new Entity.Metadata.Model();
            var entityAbstract = model.AddEntityType(typeof(Abstract));
            SetPrimaryKey(entityAbstract);
            var entityGeneric = model.AddEntityType(typeof(Generic<string>));
            entityGeneric.BaseType = entityAbstract;

            var discriminatorProperty = entityAbstract.AddProperty("D", typeof(int));
            entityAbstract.Relational().DiscriminatorProperty = discriminatorProperty;
            entityAbstract.Relational().DiscriminatorValue = 0;
            
            VerifyError(RelationalStrings.NoDiscriminatorValue(entityGeneric.DisplayName()), model);
        }
Esempio n. 10
0
        public virtual void Detects_missing_discriminator_value_on_base()
        {
            var model          = new Entity.Metadata.Model();
            var entityA        = model.AddEntityType(typeof(A));
            var entityAbstract = model.AddEntityType(typeof(Abstract));

            entityAbstract.BaseType = entityA;

            var discriminatorProperty = entityA.AddProperty("D", typeof(int));

            entityA.Relational().DiscriminatorProperty     = discriminatorProperty;
            entityAbstract.Relational().DiscriminatorValue = 1;

            VerifyError(Strings.NoDiscriminatorValue(entityA.DisplayName()), model);
        }
        public virtual void Does_not_detect_duplicate_table_names_for_inherited_entities()
        {
            var model = new Entity.Metadata.Model();
            var entityA = model.AddEntityType(typeof(A));
            SetPrimaryKey(entityA);
            var entityC = model.AddEntityType(typeof(C));
            entityC.BaseType = entityA;

            var discriminatorProperty = entityA.AddProperty("D", typeof(int));
            entityA.Relational().DiscriminatorProperty = discriminatorProperty;
            entityA.Relational().DiscriminatorValue = 0;
            entityC.Relational().DiscriminatorValue = 1;

            CreateModelValidator().Validate(model);
        }
Esempio n. 12
0
        private static IModel CreateModel()
        {
            var model = new Entity.Metadata.Model {
                StorageName = "MyDatabase"
            };

            var dependentEntityType = model.AddEntityType("Dependent");

            dependentEntityType.Relational().Schema = "dbo";
            dependentEntityType.Relational().Table  = "MyTable0";

            var principalEntityType = model.AddEntityType("Principal");

            principalEntityType.Relational().Schema = "dbo";
            principalEntityType.Relational().Table  = "MyTable1";

            var dependentProperty = dependentEntityType.GetOrAddProperty("Id", typeof(int), shadowProperty: true);
            var principalProperty = principalEntityType.GetOrAddProperty("Id", typeof(int), shadowProperty: true);

            principalProperty.ValueGeneration = ValueGeneration.OnAdd;

            principalProperty.Relational().ColumnType = "int";
            dependentProperty.Relational().ColumnType = "int";

            dependentEntityType.GetOrSetPrimaryKey(dependentProperty);
            principalEntityType.GetOrSetPrimaryKey(principalProperty);
            dependentEntityType.GetPrimaryKey().Relational().Name = "MyPK0";
            principalEntityType.GetPrimaryKey().Relational().Name = "MyPK1";

            var foreignKey = dependentEntityType.GetOrAddForeignKey(dependentProperty, principalEntityType.GetPrimaryKey());

            foreignKey.Relational().Name = "MyFK";
            // TODO: Cascading behaviors not supported. Issue #333
            //foreignKey.Annotations.Add(new Annotation(
            //    MetadataExtensions.Annotations.CascadeDelete, "True"));

            var index = dependentEntityType.GetOrAddIndex(dependentProperty);

            index.Relational().Name = "MyIndex";
            index.IsUnique = true;

            var stringProperty = principalEntityType.GetOrAddProperty("Name", typeof(string), shadowProperty: true);

            stringProperty.MaxLength = 256;

            return(model);
        }
Esempio n. 13
0
        public virtual void Passes_for_non_hierarchical_model()
        {
            var model = new Entity.Metadata.Model();

            model.AddEntityType(typeof(A));

            CreateModelValidator().Validate(model);
        }
Esempio n. 14
0
        public virtual void AddEntityTypesToModel([NotNull] Entity.Metadata.Model relationalModel)
        {
            Check.NotNull(relationalModel, nameof(relationalModel));

            foreach (var table in _tables.Values)
            {
                var entityType = relationalModel.AddEntityType(table.Id);
                _tableIdToEntityType.Add(table.Id, entityType);
                entityType.Relational().TableName = _tables[table.Id].TableName;
                entityType.Relational().Schema    = _tables[table.Id].SchemaName;
            }
        }
        //TODO: investigate doing this as a builder pattern
        public virtual IModel ConstructCodeGenModel(
            [NotNull] IModel relationalModel, [NotNull] MetadataModelNameMapper nameMapper)
        {
            Check.NotNull(relationalModel, nameof(relationalModel));
            Check.NotNull(nameMapper, nameof(nameMapper));

            var codeGenModel = new Entity.Metadata.Model();

            foreach (var relationalEntityType in relationalModel.EntityTypes.Cast <EntityType>())
            {
                var codeGenEntityType = codeGenModel
                                        .AddEntityType(nameMapper.EntityTypeToClassNameMap[relationalEntityType]);
                _relationalToCodeGenEntityTypeMap[relationalEntityType] = codeGenEntityType;
                codeGenEntityType.Relational().TableName = relationalEntityType.Relational().TableName;
                codeGenEntityType.Relational().Schema    = relationalEntityType.Relational().Schema;
                var errorMessage = relationalEntityType[AnnotationNameEntityTypeError];
                if (errorMessage != null)
                {
                    codeGenEntityType.AddAnnotation(AnnotationNameEntityTypeError,
                                                    Strings.UnableToGenerateEntityType(codeGenEntityType.Name, errorMessage));
                }

                foreach (var relationalProperty in relationalEntityType.Properties)
                {
                    var codeGenProperty = codeGenEntityType.AddProperty(
                        nameMapper.PropertyToPropertyNameMap[relationalProperty],
                        ((IProperty)relationalProperty).ClrType);
                    _relationalToCodeGenPropertyMap[relationalProperty] = codeGenProperty;
                    CopyPropertyFacets(relationalProperty, codeGenProperty);
                }


                var primaryKey = relationalEntityType.FindPrimaryKey();
                if (primaryKey != null)
                {
                    codeGenEntityType.SetPrimaryKey(
                        primaryKey.Properties
                        .Select(p => _relationalToCodeGenPropertyMap[p])
                        .ToList());
                }
            } // end of loop over all relational EntityTypes

            AddForeignKeysToCodeGenModel(relationalModel, codeGenModel);

            return(codeGenModel);
        }
Esempio n. 16
0
        private static IModel BuildModel(ValueGeneration keyStrategy, ValueGeneration nonKeyStrategy)
        {
            var model = new Entity.Metadata.Model();

            var entityType = model.AddEntityType(typeof(T1));

            var key = entityType.GetOrAddProperty("Id", typeof(int));

            key.ValueGeneration = keyStrategy;
            key.Relational().Column = "Col1";
            entityType.GetOrSetPrimaryKey(key);

            var nonKey = entityType.GetOrAddProperty("Name", typeof(string));

            nonKey.Relational().Column = "Col2";
            nonKey.ValueGeneration = nonKeyStrategy;

            return(model);
        }
        private static IModel BuildModel(bool generateKeyValues, bool computeNonKeyValue)
        {
            var model = new Entity.Metadata.Model();

            var entityType = model.AddEntityType(typeof(T1));

            var key = entityType.GetOrAddProperty("Id", typeof(int));

            key.GenerateValueOnAdd = generateKeyValues;
            key.Relational().Column = "Col1";
            entityType.GetOrSetPrimaryKey(key);

            var nonKey = entityType.GetOrAddProperty("Name", typeof(string));

            nonKey.Relational().Column = "Col2";
            nonKey.IsStoreComputed = computeNonKeyValue;

            return(model);
        }
Esempio n. 18
0
        private static IModel BuildModel(bool generateKeyValues, bool computeNonKeyValue)
        {
            var model      = new Entity.Metadata.Model();
            var entityType = model.AddEntityType(typeof(T1));

            var key = entityType.GetOrAddProperty("Id", typeof(int));

            key.ValueGenerated = generateKeyValues ? ValueGenerated.OnAdd : ValueGenerated.Never;
            key.Relational().Column = "Col1";
            entityType.GetOrSetPrimaryKey(key);

            var nonKey = entityType.GetOrAddProperty("Name", typeof(string));

            nonKey.IsConcurrencyToken = computeNonKeyValue;

            nonKey.Relational().Column = "Col2";
            nonKey.ValueGenerated = computeNonKeyValue ? ValueGenerated.OnAddOrUpdate : ValueGenerated.Never;

            return(model);
        }
Esempio n. 19
0
        public virtual IModel ConstructRelationalModel()
        {
            var relationalModel = new Entity.Metadata.Model();

            foreach (var table in _tables.Values)
            {
                relationalModel.AddEntityType(table.Id);
            }

            foreach (var tc in _tableColumns.Values)
            {
                var entityType = relationalModel.FindEntityType(tc.TableId);
                if (entityType == null)
                {
                    _logger.LogWarning(
                        Strings.CannotFindTableForColumn(tc.Id, tc.TableId));
                    continue;
                }

                // IModel will not allow Properties to be created without a Type, so map to CLR type here.
                // This means if we come across a column with a SQL Server type which we can't map we will ignore it.
                // Note: foreign key properties appear just like any other property in the relational model.
                Type clrPropertyType;
                if (!SqlServerTypeMapping._sqlTypeToClrTypeMap.TryGetValue(tc.DataType, out clrPropertyType))
                {
                    _logger.LogWarning(
                        Strings.CannotFindTypeMappingForColumn(tc.Id, tc.DataType));
                    continue;
                }

                if (tc.IsNullable)
                {
                    clrPropertyType = clrPropertyType.MakeNullable();
                }

                var relationalProperty = entityType.AddProperty(tc.Id, clrPropertyType, shadowProperty: true);
                _relationalColumnIdToRelationalPropertyMap[tc.Id] = relationalProperty;
            }

            return(relationalModel);
        }
        private static IModel BuildModel(bool generateKeyValues, bool computeNonKeyValue)
        {
            var model = new Entity.Metadata.Model();

            var entityType = model.AddEntityType(typeof(T1));

            var key = entityType.AddProperty("Id", typeof(int));
            key.IsShadowProperty = false;
            key.ValueGenerated = generateKeyValues ? ValueGenerated.OnAdd : ValueGenerated.Never;
            key.Relational().ColumnName = "Col1";
            entityType.GetOrSetPrimaryKey(key);

            var nonKey = entityType.AddProperty("Name", typeof(string));
            nonKey.IsShadowProperty = false;
            nonKey.Relational().ColumnName = "Col2";
            nonKey.ValueGenerated = computeNonKeyValue ? ValueGenerated.OnAddOrUpdate : ValueGenerated.Never;

            return model;
        }
        public void Compare_returns_0_only_for_commands_that_are_equal()
        {
            var model = new Entity.Metadata.Model();
            var entityType = model.AddEntityType(typeof(object));

            var optionsBuilder = new DbContextOptionsBuilder()
                .UseModel(model);
            optionsBuilder.UseInMemoryStore(persist: false);

            var contextServices = ((IAccessor<IServiceProvider>)new DbContext(optionsBuilder.Options)).Service;
            var stateManager = contextServices.GetRequiredService<IStateManager>();

            var key = entityType.GetOrAddProperty("Id", typeof(int), shadowProperty: true);
            entityType.GetOrSetPrimaryKey(key);

            var entry1 = stateManager.GetOrCreateEntry(new object());
            entry1[key] = 1;
            entry1.SetEntityState(EntityState.Added);
            var modificationCommandAdded = new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new BoxedValueReaderSource());
            modificationCommandAdded.AddEntry(entry1);

            var entry2 = stateManager.GetOrCreateEntry(new object());
            entry2[key] = 2;
            entry2.SetEntityState(EntityState.Modified);
            var modificationCommandModified = new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new BoxedValueReaderSource());
            modificationCommandModified.AddEntry(entry2);

            var entry3 = stateManager.GetOrCreateEntry(new object());
            entry3[key] = 3;
            entry3.SetEntityState(EntityState.Deleted);
            var modificationCommandDeleted = new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new BoxedValueReaderSource());
            modificationCommandDeleted.AddEntry(entry3);

            var mCC = new ModificationCommandComparer();

            Assert.True(0 == mCC.Compare(modificationCommandAdded, modificationCommandAdded));
            Assert.True(0 == mCC.Compare(null, null));
            Assert.True(0 == mCC.Compare(
                new ModificationCommand("A", "dbo", new ParameterNameGenerator(), p => p.Relational(), new BoxedValueReaderSource()),
                new ModificationCommand("A", "dbo", new ParameterNameGenerator(), p => p.Relational(), new BoxedValueReaderSource())));

            Assert.True(0 > mCC.Compare(null, new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new BoxedValueReaderSource())));
            Assert.True(0 < mCC.Compare(new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new BoxedValueReaderSource()), null));

            Assert.True(0 > mCC.Compare(
                new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new BoxedValueReaderSource()),
                new ModificationCommand("A", "dbo", new ParameterNameGenerator(), p => p.Relational(), new BoxedValueReaderSource())));
            Assert.True(0 < mCC.Compare(
                new ModificationCommand("A", "dbo", new ParameterNameGenerator(), p => p.Relational(), new BoxedValueReaderSource()),
                new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new BoxedValueReaderSource())));

            Assert.True(0 > mCC.Compare(
                new ModificationCommand("A", "dbo", new ParameterNameGenerator(), p => p.Relational(), new BoxedValueReaderSource()),
                new ModificationCommand("A", "foo", new ParameterNameGenerator(), p => p.Relational(), new BoxedValueReaderSource())));
            Assert.True(0 < mCC.Compare(
                new ModificationCommand("A", "foo", new ParameterNameGenerator(), p => p.Relational(), new BoxedValueReaderSource()),
                new ModificationCommand("A", "dbo", new ParameterNameGenerator(), p => p.Relational(), new BoxedValueReaderSource())));

            Assert.True(0 > mCC.Compare(
                new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new BoxedValueReaderSource()),
                new ModificationCommand("B", null, new ParameterNameGenerator(), p => p.Relational(), new BoxedValueReaderSource())));
            Assert.True(0 < mCC.Compare(
                new ModificationCommand("B", null, new ParameterNameGenerator(), p => p.Relational(), new BoxedValueReaderSource()),
                new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new BoxedValueReaderSource())));

            Assert.True(0 > mCC.Compare(modificationCommandModified, modificationCommandAdded));
            Assert.True(0 < mCC.Compare(modificationCommandAdded, modificationCommandModified));

            Assert.True(0 > mCC.Compare(modificationCommandDeleted, modificationCommandAdded));
            Assert.True(0 < mCC.Compare(modificationCommandAdded, modificationCommandDeleted));

            Assert.True(0 > mCC.Compare(modificationCommandDeleted, modificationCommandModified));
            Assert.True(0 < mCC.Compare(modificationCommandModified, modificationCommandDeleted));
        }
        //TODO: investigate doing this as a builder pattern
        public virtual IModel ConstructCodeGenModel(
            [NotNull] IModel relationalModel, [NotNull] MetadataModelNameMapper nameMapper)
        {
            Check.NotNull(relationalModel, nameof(relationalModel));
            Check.NotNull(nameMapper, nameof(nameMapper));

            var codeGenModel = new Entity.Metadata.Model();
            foreach (var relationalEntityType in relationalModel.EntityTypes.Cast<EntityType>())
            {
                var codeGenEntityType = codeGenModel
                    .AddEntityType(nameMapper.EntityTypeToClassNameMap[relationalEntityType]);
                _relationalToCodeGenEntityTypeMap[relationalEntityType] = codeGenEntityType;
                codeGenEntityType.Relational().TableName = relationalEntityType.Relational().TableName;
                codeGenEntityType.Relational().Schema = relationalEntityType.Relational().Schema;
                var errorMessage = relationalEntityType[AnnotationNameEntityTypeError];
                if (errorMessage != null)
                {
                    codeGenEntityType.AddAnnotation(AnnotationNameEntityTypeError, 
                        Strings.UnableToGenerateEntityType(codeGenEntityType.Name, errorMessage));
                }

                foreach (var relationalProperty in relationalEntityType.Properties)
                {
                    var codeGenProperty = codeGenEntityType.AddProperty(
                        nameMapper.PropertyToPropertyNameMap[relationalProperty],
                        ((IProperty)relationalProperty).ClrType);
                    _relationalToCodeGenPropertyMap[relationalProperty] = codeGenProperty;
                    CopyPropertyFacets(relationalProperty, codeGenProperty);
                }


                var primaryKey = relationalEntityType.FindPrimaryKey();
                if (primaryKey != null)
                {
                    codeGenEntityType.SetPrimaryKey(
                        primaryKey.Properties
                            .Select(p => _relationalToCodeGenPropertyMap[p])
                            .ToList());
                }
            } // end of loop over all relational EntityTypes

            AddForeignKeysToCodeGenModel(relationalModel, codeGenModel);

            return codeGenModel;
        }
        public void Compare_returns_0_only_for_commands_that_are_equal()
        {
            var model      = new Entity.Metadata.Model();
            var entityType = model.AddEntityType(typeof(object));

            var contextServices = ((IDbContextServices) new DbContext(
                                       new DbContextOptions()
                                       .UseModel(model)
                                       .UseInMemoryStore(persist: false))).ScopedServiceProvider;
            var stateManager = contextServices.GetRequiredService <StateManager>();

            var key = entityType.GetOrAddProperty("Id", typeof(int), shadowProperty: true);

            entityType.GetOrSetPrimaryKey(key);

            var stateEntry1 = stateManager.GetOrCreateEntry(new object());

            stateEntry1[key]        = 0;
            stateEntry1.EntityState = EntityState.Added;
            var modificationCommandAdded = new ModificationCommand(new SchemaQualifiedName("A"), new ParameterNameGenerator(), p => p.Relational());

            modificationCommandAdded.AddStateEntry(stateEntry1);

            var stateEntry2 = stateManager.GetOrCreateEntry(new object());

            stateEntry2[key]        = 1;
            stateEntry2.EntityState = EntityState.Modified;
            var modificationCommandModified = new ModificationCommand(new SchemaQualifiedName("A"), new ParameterNameGenerator(), p => p.Relational());

            modificationCommandModified.AddStateEntry(stateEntry2);

            var stateEntry3 = stateManager.GetOrCreateEntry(new object());

            stateEntry3[key]        = 2;
            stateEntry3.EntityState = EntityState.Deleted;
            var modificationCommandDeleted = new ModificationCommand(new SchemaQualifiedName("A"), new ParameterNameGenerator(), p => p.Relational());

            modificationCommandDeleted.AddStateEntry(stateEntry3);

            var mCC = new ModificationCommandComparer();

            Assert.True(0 == mCC.Compare(modificationCommandAdded, modificationCommandAdded));
            Assert.True(0 == mCC.Compare(null, null));
            Assert.True(0 == mCC.Compare(
                            new ModificationCommand(new SchemaQualifiedName("A", "dbo"), new ParameterNameGenerator(), p => p.Relational()),
                            new ModificationCommand(new SchemaQualifiedName("A", "dbo"), new ParameterNameGenerator(), p => p.Relational())));

            Assert.True(0 > mCC.Compare(null, new ModificationCommand(new SchemaQualifiedName("A"), new ParameterNameGenerator(), p => p.Relational())));
            Assert.True(0 < mCC.Compare(new ModificationCommand(new SchemaQualifiedName("A"), new ParameterNameGenerator(), p => p.Relational()), null));

            Assert.True(0 > mCC.Compare(
                            new ModificationCommand(new SchemaQualifiedName("A"), new ParameterNameGenerator(), p => p.Relational()),
                            new ModificationCommand(new SchemaQualifiedName("A", "dbo"), new ParameterNameGenerator(), p => p.Relational())));
            Assert.True(0 < mCC.Compare(
                            new ModificationCommand(new SchemaQualifiedName("A", "dbo"), new ParameterNameGenerator(), p => p.Relational()),
                            new ModificationCommand(new SchemaQualifiedName("A"), new ParameterNameGenerator(), p => p.Relational())));

            Assert.True(0 > mCC.Compare(
                            new ModificationCommand(new SchemaQualifiedName("A", "dbo"), new ParameterNameGenerator(), p => p.Relational()),
                            new ModificationCommand(new SchemaQualifiedName("A", "foo"), new ParameterNameGenerator(), p => p.Relational())));
            Assert.True(0 < mCC.Compare(
                            new ModificationCommand(new SchemaQualifiedName("A", "foo"), new ParameterNameGenerator(), p => p.Relational()),
                            new ModificationCommand(new SchemaQualifiedName("A", "dbo"), new ParameterNameGenerator(), p => p.Relational())));

            Assert.True(0 > mCC.Compare(
                            new ModificationCommand(new SchemaQualifiedName("A"), new ParameterNameGenerator(), p => p.Relational()),
                            new ModificationCommand(new SchemaQualifiedName("B"), new ParameterNameGenerator(), p => p.Relational())));
            Assert.True(0 < mCC.Compare(
                            new ModificationCommand(new SchemaQualifiedName("B"), new ParameterNameGenerator(), p => p.Relational()),
                            new ModificationCommand(new SchemaQualifiedName("A"), new ParameterNameGenerator(), p => p.Relational())));

            Assert.True(0 > mCC.Compare(modificationCommandModified, modificationCommandAdded));
            Assert.True(0 < mCC.Compare(modificationCommandAdded, modificationCommandModified));

            Assert.True(0 > mCC.Compare(modificationCommandDeleted, modificationCommandAdded));
            Assert.True(0 < mCC.Compare(modificationCommandAdded, modificationCommandDeleted));

            Assert.True(0 > mCC.Compare(modificationCommandDeleted, modificationCommandModified));
            Assert.True(0 < mCC.Compare(modificationCommandModified, modificationCommandDeleted));
        }
Esempio n. 24
0
        public virtual IModel ConstructCodeGenModel(
            [NotNull] IModel relationalModel, [NotNull] MetadataModelNameMapper nameMapper)
        {
            Check.NotNull(relationalModel, nameof(relationalModel));
            Check.NotNull(nameMapper, nameof(nameMapper));

            var codeGenModel = new Entity.Metadata.Model();

            foreach (var relationalEntityType in relationalModel.EntityTypes.Cast <EntityType>())
            {
                var codeGenEntityType = codeGenModel
                                        .AddEntityType(nameMapper.EntityTypeToClassNameMap[relationalEntityType]);
                _relationalEntityTypeToCodeGenEntityTypeMap[relationalEntityType] = codeGenEntityType;
                codeGenEntityType.Relational().Table  = _tables[relationalEntityType.Name].TableName;
                codeGenEntityType.Relational().Schema = _tables[relationalEntityType.Name].SchemaName;

                // Loop over relational properties constructing a matching property in the
                // codeGenModel. Also accumulate:
                //    a) primary key properties
                //    b) constraint properties
                var primaryKeyProperties = new List <Property>();
                var constraints          = new Dictionary <string, List <Property> >();
                _relationalEntityTypeToForeignKeyConstraintsMap[relationalEntityType] = constraints;
                foreach (var relationalProperty in relationalEntityType.Properties)
                {
                    int primaryKeyOrdinal;
                    if (_primaryKeyOrdinals.TryGetValue(relationalProperty.Name, out primaryKeyOrdinal))
                    {
                        // add _relational_ property so we can order on the ordinal later
                        primaryKeyProperties.Add(relationalProperty);
                    }

                    Dictionary <string, int> foreignKeyConstraintIdOrdinalMap;
                    if (_foreignKeyOrdinals.TryGetValue(relationalProperty.Name, out foreignKeyConstraintIdOrdinalMap))
                    {
                        // relationalProperty represents (part of) a foreign key
                        foreach (var constraintId in foreignKeyConstraintIdOrdinalMap.Keys)
                        {
                            List <Property> constraintProperties;
                            if (!constraints.TryGetValue(constraintId, out constraintProperties))
                            {
                                constraintProperties = new List <Property>();
                                constraints.Add(constraintId, constraintProperties);
                            }
                            constraintProperties.Add(relationalProperty);
                        }
                    }

                    var codeGenProperty = codeGenEntityType.AddProperty(
                        nameMapper.PropertyToPropertyNameMap[relationalProperty],
                        relationalProperty.ClrType,
                        shadowProperty: true);
                    _relationalPropertyToCodeGenPropertyMap[relationalProperty] = codeGenProperty;
                    ApplyPropertyProperties(codeGenProperty, _tableColumns[relationalProperty.Name]);
                } // end of loop over all relational properties for given EntityType

                if (primaryKeyProperties.Count() > 0)
                {
                    // order the relational properties by their primaryKeyOrdinal, then return a list
                    // of the codeGen properties mapped to each relational property in that order
                    codeGenEntityType.SetPrimaryKey(
                        primaryKeyProperties
                        .OrderBy(p => _primaryKeyOrdinals[p.Name])     // note: for relational property p.Name is its columnId
                        .Select(p => _relationalPropertyToCodeGenPropertyMap[p])
                        .ToList());
                }
                else
                {
                    var errorMessage = Strings.NoPrimaryKeyColumns(
                        codeGenEntityType.Name,
                        _tables[relationalEntityType.Name].SchemaName,
                        _tables[relationalEntityType.Name].TableName);
                    codeGenEntityType.AddAnnotation(AnnotationNameEntityTypeError, errorMessage);
                    _logger.LogWarning(Strings.CannotGenerateEntityType(codeGenEntityType.Name, errorMessage));
                }
            } // end of loop over all relational EntityTypes

            AddForeignKeysToCodeGenModel(codeGenModel);

            return(codeGenModel);
        }
        private static IModel BuildModel(bool generateKeyValues, bool computeNonKeyValue)
        {
            var model = new Entity.Metadata.Model();

            var entityType = model.AddEntityType(typeof(T1));

            var key = entityType.GetOrAddProperty("Id", typeof(int));
            key.StoreGeneratedPattern = generateKeyValues ? StoreGeneratedPattern.Identity : StoreGeneratedPattern.None;
            key.GenerateValueOnAdd = generateKeyValues;
            key.Relational().Column = "Col1";
            entityType.GetOrSetPrimaryKey(key);

            var nonKey = entityType.GetOrAddProperty("Name", typeof(string));
            nonKey.Relational().Column = "Col2";
            nonKey.StoreGeneratedPattern = computeNonKeyValue ? StoreGeneratedPattern.Computed : StoreGeneratedPattern.None;

            return model;
        }
Esempio n. 26
0
        public void Compare_returns_0_only_for_commands_that_are_equal()
        {
            var model      = new Entity.Metadata.Model();
            var entityType = model.AddEntityType(typeof(object));

            var optionsBuilder = new EntityOptionsBuilder()
                                 .UseModel(model);

            optionsBuilder.UseInMemoryStore(persist: false);

            var contextServices = ((IAccessor <IServiceProvider>) new DbContext(optionsBuilder.Options)).Service;
            var stateManager    = contextServices.GetRequiredService <IStateManager>();

            var key = entityType.GetOrAddProperty("Id", typeof(int), shadowProperty: true);

            entityType.GetOrSetPrimaryKey(key);

            var entry1 = stateManager.GetOrCreateEntry(new object());

            entry1[key] = 1;
            entry1.SetEntityState(EntityState.Added);
            var modificationCommandAdded = new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory());

            modificationCommandAdded.AddEntry(entry1);

            var entry2 = stateManager.GetOrCreateEntry(new object());

            entry2[key] = 2;
            entry2.SetEntityState(EntityState.Modified);
            var modificationCommandModified = new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory());

            modificationCommandModified.AddEntry(entry2);

            var entry3 = stateManager.GetOrCreateEntry(new object());

            entry3[key] = 3;
            entry3.SetEntityState(EntityState.Deleted);
            var modificationCommandDeleted = new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory());

            modificationCommandDeleted.AddEntry(entry3);

            var mCC = new ModificationCommandComparer();

            Assert.True(0 == mCC.Compare(modificationCommandAdded, modificationCommandAdded));
            Assert.True(0 == mCC.Compare(null, null));
            Assert.True(0 == mCC.Compare(
                            new ModificationCommand("A", "dbo", new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()),
                            new ModificationCommand("A", "dbo", new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory())));

            Assert.True(0 > mCC.Compare(null, new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory())));
            Assert.True(0 < mCC.Compare(new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()), null));

            Assert.True(0 > mCC.Compare(
                            new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()),
                            new ModificationCommand("A", "dbo", new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory())));
            Assert.True(0 < mCC.Compare(
                            new ModificationCommand("A", "dbo", new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()),
                            new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory())));

            Assert.True(0 > mCC.Compare(
                            new ModificationCommand("A", "dbo", new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()),
                            new ModificationCommand("A", "foo", new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory())));
            Assert.True(0 < mCC.Compare(
                            new ModificationCommand("A", "foo", new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()),
                            new ModificationCommand("A", "dbo", new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory())));

            Assert.True(0 > mCC.Compare(
                            new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()),
                            new ModificationCommand("B", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory())));
            Assert.True(0 < mCC.Compare(
                            new ModificationCommand("B", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()),
                            new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory())));

            Assert.True(0 > mCC.Compare(modificationCommandModified, modificationCommandAdded));
            Assert.True(0 < mCC.Compare(modificationCommandAdded, modificationCommandModified));

            Assert.True(0 > mCC.Compare(modificationCommandDeleted, modificationCommandAdded));
            Assert.True(0 < mCC.Compare(modificationCommandAdded, modificationCommandDeleted));

            Assert.True(0 > mCC.Compare(modificationCommandDeleted, modificationCommandModified));
            Assert.True(0 < mCC.Compare(modificationCommandModified, modificationCommandDeleted));
        }