public virtual void Apply(InternalEntityTypeBuilder entityTypeBuilder, ForeignKey foreignKey)
        {
            Check.NotNull(entityTypeBuilder, nameof(entityTypeBuilder));
            Check.NotNull(foreignKey, nameof(foreignKey));

            var properties = foreignKey.Properties;

            if (properties.Any(e => e.GenerateValueOnAdd == true))
            {
                ConfigureValueGenerationStrategy(entityTypeBuilder, properties, true);
            }
        }
Ejemplo n.º 2
0
 public IEnumerable<string> AddForeignKey(string tableName, string referencedTableName, IEnumerable<ColumnReference> columnNames, string constraintName)
 {
     Table table = GetTable(tableName);
     ForeignKey foreignKey = new ForeignKey(table, constraintName) { ReferencedTable = referencedTableName };
     foreach (ColumnReference columnReference in columnNames)
     {
         var fromColumn = new Microsoft.SqlServer.Management.Smo.Column(table, columnReference.ColumnName);
         table.Columns.Add(fromColumn);
         var foreignKeyColumn = new ForeignKeyColumn(foreignKey, columnReference.ColumnName, columnReference.ReferencedColumnName);
         foreignKey.Columns.Add(foreignKeyColumn);
     }
     foreignKey.Create();
     return ScriptChanges(table.Parent.Parent);
 }
Ejemplo n.º 3
0
        public void Can_create_foreign_key()
        {
            var entityType = new Model().AddEntityType("E");
            var dependentProp = entityType.AddProperty("P", typeof(int));
            var principalProp = entityType.AddProperty("Id", typeof(int));
            entityType.GetOrSetPrimaryKey(principalProp);

            var foreignKey
                = new ForeignKey(new[] { dependentProp }, entityType.GetPrimaryKey(), entityType, entityType)
                    {
                        IsUnique = true
                    };

            Assert.Same(entityType, foreignKey.PrincipalEntityType);
            Assert.Same(principalProp, foreignKey.PrincipalKey.Properties.Single());
            Assert.Same(dependentProp, foreignKey.Properties.Single());
            Assert.True(foreignKey.IsUnique.Value);
            Assert.Same(entityType.GetPrimaryKey(), foreignKey.PrincipalKey);
        }
        public IList<ForeignKey> DetermineForeignKeyReferences(Table table)
        {
            var constraints = table.Columns.Where(x => x.IsForeignKey.Equals(true)).Select(x => x.ConstraintName).Distinct().ToList();
            var foreignKeys = new List<ForeignKey>();
            constraints.ForEach(c =>
                {
                    var fkColumns = table.Columns.Where(x => x.ConstraintName.Equals(c)).ToArray();
                    var fk = new ForeignKey
                        {
                            Name = fkColumns[0].Name,
                            References = GetForeignKeyReferenceTableName(table.Owner, table.Name, fkColumns[0].Name),
                            Columns = fkColumns
                        };
                    foreignKeys.Add(fk);
                });

            Table.SetUniqueNamesForForeignKeyProperties(foreignKeys);

            return foreignKeys;
        }
Ejemplo n.º 5
0
        //My Method
        public MetaDataPhysical getMetaDataPhysical()
        {
            //Convert tất cả shape qua MetaDataPhysical
            MetaDataPhysical mdp = new MetaDataPhysical();

            //Duyệt tất cả controls trên Panel
            foreach (Control ctr in this.Controls)
            {
                TableShape tShape = (TableShape)ctr;
                mdp.Tables.Add(tShape.table);
                foreach (FKShape fkShape in tShape.listFK)
                {
                    ForeignKey fk = new ForeignKey();
                    fk.Name = fkShape.fkName;
                    fk.ParentTable = tShape.table.name;
                    fk.ParentColumn = fkShape.parentColumn;
                    fk.ChildTable = fkShape.tableReference.table.name;
                    fk.ChildColumn = fkShape.childColumn;
                    mdp.ForeignKeys.Add(fk);
                }
            }
            return mdp;
        }
Ejemplo n.º 6
0
 bool IsSelfReference(ForeignKey foreignKey, ForeignKey refTableForeignKey) {
     return refTableForeignKey.Parent.Name==foreignKey.Parent.Name;
 }
Ejemplo n.º 7
0
 public bool IsOneToOne(ForeignKey foreignKey, string referenceColumn) {
     var refTableForeignKey = GetRefTableForeignKey(foreignKey, referenceColumn);
     return refTableForeignKey != null&&!IsSelfReference(foreignKey, refTableForeignKey);
 }
Ejemplo n.º 8
0
		protected override IEnumerable<DbParameter> CoreGetForeignKeyColumnParameters(Type connectionType, string dataSourceTag, Server server, Database database, Schema schema, Table table, ForeignKey foreignKey)
		{
			if ((object)connectionType == null)
				throw new ArgumentNullException(nameof(connectionType));

			if ((object)dataSourceTag == null)
				throw new ArgumentNullException(nameof(dataSourceTag));

			if ((object)server == null)
				throw new ArgumentNullException(nameof(server));

			if ((object)database == null)
				throw new ArgumentNullException(nameof(database));

			if ((object)schema == null)
				throw new ArgumentNullException(nameof(schema));

			if ((object)table == null)
				throw new ArgumentNullException(nameof(table));

			if ((object)foreignKey == null)
				throw new ArgumentNullException(nameof(foreignKey));

			if (dataSourceTag.SafeToString().ToLower() == ODBC_SQL_SERVER_DATA_SOURCE_TAG)
			{
				return new DbParameter[]
						{
							//DatazoidLegacyInstanceAccessor.AdoNetBufferingLegacyInstance.CreateParameter(connectionType, null,ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P1", server.ServerName),
							//DatazoidLegacyInstanceAccessor.AdoNetBufferingLegacyInstance.CreateParameter(connectionType, null,ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P2", database.DatabaseName),
							DatazoidLegacyInstanceAccessor.AdoNetBufferingLegacyInstance.CreateParameter(connectionType, null, ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P3", schema.SchemaName),
							//DatazoidLegacyInstanceAccessor.AdoNetBufferingLegacyInstance.CreateParameter(connectionType, null,ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P4", table.TableName),
							DatazoidLegacyInstanceAccessor.AdoNetBufferingLegacyInstance.CreateParameter(connectionType, null, ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P5", foreignKey.ForeignKeyName)
						};
			}

			throw new ArgumentOutOfRangeException(string.Format("dataSourceTag: '{0}'", dataSourceTag));
		}
        public virtual ForeignKey AddForeignKey(ForeignKey foreignKey)
        {
            if (ConstraintExists(foreignKey.ForeignTable, foreignKey.Name))
                throw new ForeignKeyAlreadyExistsException(foreignKey.ForeignTable, foreignKey.Name);

            foreignKey.PrimaryTable = QuoteTableNameIfRequired(foreignKey.PrimaryTable);
            foreignKey.ForeignTable = QuoteTableNameIfRequired(foreignKey.ForeignTable);
            QuoteColumnNames(foreignKey.ForeignColumns);
            QuoteColumnNames(foreignKey.PrimaryColumns);

            string constraintResolved = _constraintMapper.SqlForConstraint(foreignKey.ConstraintType);

            ExecuteNonQuery(
                String.Format(
                    "ALTER TABLE {0} ADD CONSTRAINT {1} FOREIGN KEY ({2}) REFERENCES {3} ({4}) ON UPDATE {5} ON DELETE {6}",
                    foreignKey.ForeignTable, foreignKey.Name, String.Join(",", foreignKey.ForeignColumns),
                    foreignKey.PrimaryTable, String.Join(",", foreignKey.PrimaryColumns), constraintResolved,
                    constraintResolved));


            return foreignKey;
        }
Ejemplo n.º 10
0
        protected override IEnumerable <DbParameter> CoreGetForeignKeyColumnParameters(Type connectionType, string dataSourceTag, Server server, Database database, Schema schema, Table table, ForeignKey foreignKey)
        {
            if ((object)connectionType == null)
            {
                throw new ArgumentNullException(nameof(connectionType));
            }

            if ((object)dataSourceTag == null)
            {
                throw new ArgumentNullException(nameof(dataSourceTag));
            }

            if ((object)server == null)
            {
                throw new ArgumentNullException(nameof(server));
            }

            if ((object)database == null)
            {
                throw new ArgumentNullException(nameof(database));
            }

            if ((object)schema == null)
            {
                throw new ArgumentNullException(nameof(schema));
            }

            if ((object)table == null)
            {
                throw new ArgumentNullException(nameof(table));
            }

            if ((object)foreignKey == null)
            {
                throw new ArgumentNullException(nameof(foreignKey));
            }

            if (dataSourceTag.SafeToString().ToLower() == NET_SQL_SERVER_DATA_SOURCE_TAG)
            {
                return(new DbParameter[]
                {
                    SolderFascadeAccessor.AdoNetBufferingFascade.CreateParameter(connectionType, null, ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@ServerName", server.ServerName),
                    SolderFascadeAccessor.AdoNetBufferingFascade.CreateParameter(connectionType, null, ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@DatabaseName", database.DatabaseName),
                    SolderFascadeAccessor.AdoNetBufferingFascade.CreateParameter(connectionType, null, ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@SchemaName", schema.SchemaName),
                    SolderFascadeAccessor.AdoNetBufferingFascade.CreateParameter(connectionType, null, ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@TableName", table.TableName),
                    SolderFascadeAccessor.AdoNetBufferingFascade.CreateParameter(connectionType, null, ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@ForeignKeyName", foreignKey.ForeignKeyName)
                });
            }

            throw new ArgumentOutOfRangeException(string.Format("dataSourceTag: '{0}'", dataSourceTag));
        }
Ejemplo n.º 11
0
        public void IsRequired_false_for_composite_FK_by_default()
        {
            var entityType = new Model().AddEntityType("E");
            var property = entityType.AddProperty("Id1", typeof(int));
            var property1 = entityType.AddProperty("Id2", typeof(string));
            entityType.GetOrSetPrimaryKey(new[]
                {
                    property,
                    property1
                });

            var dependentProp1 = entityType.AddProperty("P1", typeof(int));
            var dependentProp2 = entityType.AddProperty("P2", typeof(string));

            var foreignKey = new ForeignKey(new[] { dependentProp1, dependentProp2 }, entityType.GetPrimaryKey(), entityType, entityType);

            Assert.Null(foreignKey.IsRequired);
            Assert.False(((IForeignKey)foreignKey).IsRequired);
        }
        public void Main()
        {
            string query = "\n create table B1 (b_id int primary key)" +
                           "\n create table A1 (b_id int references B1(b_id))" +
                           "\n create table B2 (" +
                           "\n   b_id_1 int, " +
                           "\n   b_id_2 int, " +
                           "\n   CONSTRAINT [B2_PK] PRIMARY KEY  CLUSTERED (b_id_1, b_id_2)  ON [PRIMARY])" +
                           "\n create table A2 (" +
                           "\n   b_id_1 int,    " +
                           "\n   b_id_2 int,    " +
                           "\n   constraint [A2_FK] FOREIGN KEY (b_id_1, b_id_2) " +
                           "\n                    REFERENCES B2 (b_id_1, b_id_2) ON DELETE CASCADE ON UPDATE NO ACTION)" +
                           "\n create table B3 (" +
                           "\n   b_id_1 int," +
                           "\n   b_id_2 int," +
                           "\n   b_id_3 int," +
                           "\n   CONSTRAINT [B3_PK] PRIMARY KEY  CLUSTERED (b_id_1, b_id_2, b_id_3)  ON [PRIMARY])" +
                           "\n create table A3 (" +
                           "\n   A_col1 int," +
                           "\n   b_id_3 int," +
                           "\n   b_id_1 int," +
                           "\n   b_id_2 int," +
                           "\n   constraint [A3_FK] FOREIGN KEY (b_id_1, b_id_2, b_id_3) " +
                           "\n                    REFERENCES B3 (b_id_1, b_id_2, b_id_3) ON DELETE NO ACTION ON UPDATE CASCADE)";

            ExecuteQuery(query);


            var    model  = ExtractCatalog();
            Schema schema = model.DefaultSchema;

            // Validating.
            ForeignKey fk1 = (ForeignKey)schema.Tables["A1"].TableConstraints[0];

            Assert.IsNotNull(fk1);
            Assert.IsTrue(fk1.Columns[0].Name == "b_id");
            Assert.IsTrue(fk1.ReferencedColumns[0].Name == "b_id");
            Assert.IsTrue(fk1.ReferencedColumns.Count == 1);
            Assert.IsTrue(fk1.Columns.Count == 1);

            ForeignKey fk2 = (ForeignKey)schema.Tables["A2"].TableConstraints[0];

            Assert.IsNotNull(fk1);
            Assert.IsTrue(fk2.Name == "A2_FK");
            Assert.IsTrue(fk2.Columns[0].Name == "b_id_1");
            Assert.IsTrue(fk2.ReferencedColumns[0].Name == "b_id_1");
            Assert.IsTrue(fk2.Columns[1].Name == "b_id_2");
            Assert.IsTrue(fk2.ReferencedColumns[1].Name == "b_id_2");
            Assert.IsTrue(fk2.ReferencedColumns.Count == 2);
            Assert.IsTrue(fk2.Columns.Count == 2);
            Assert.IsTrue(fk2.OnDelete == ReferentialAction.Cascade);
            Assert.IsTrue(fk2.OnUpdate == ReferentialAction.NoAction);

            ForeignKey fk3 = (ForeignKey)schema.Tables["A3"].TableConstraints[0];

            Assert.IsNotNull(fk3);
            Assert.IsTrue(fk3.Name == "A3_FK");
            Assert.IsTrue(fk3.Columns[0].Name == "b_id_1");
            Assert.IsTrue(fk3.ReferencedColumns[0].Name == "b_id_1");
            Assert.IsTrue(fk3.Columns[1].Name == "b_id_2");
            Assert.IsTrue(fk3.ReferencedColumns[1].Name == "b_id_2");
            Assert.IsTrue(fk3.Columns[2].Name == "b_id_3");
            Assert.IsTrue(fk3.ReferencedColumns[2].Name == "b_id_3");
            Assert.IsTrue(fk3.ReferencedColumns.Count == 3);
            Assert.IsTrue(fk3.Columns.Count == 3);
            Assert.IsTrue(fk3.OnDelete == ReferentialAction.NoAction);
            Assert.IsTrue(fk3.OnUpdate == ReferentialAction.Cascade);
        }
        private IReadOnlyList <Property> TryFindMatchingClrProperties(ForeignKey foreignKey, string baseName, bool onDependent)
        {
            var entityType = onDependent
                ? foreignKey.EntityType
                : foreignKey.PrincipalEntityType;
            var propertiesToReference = onDependent
                ? foreignKey.PrincipalKey.Properties
                : foreignKey.EntityType.FindPrimaryKey()?.Properties;

            if (propertiesToReference == null)
            {
                return(null);
            }

            var foreignKeyProperties = new List <Property>();

            foreach (var referencedProperty in propertiesToReference)
            {
                var property = TryGetProperty(entityType, baseName
                                              + referencedProperty.Name, referencedProperty.ClrType.UnwrapNullableType());

                if (property != null)
                {
                    foreignKeyProperties.Add(property);
                }
            }

            if (propertiesToReference.Count == 1 &&
                foreignKeyProperties.Count == 0)
            {
                var property = TryGetProperty(entityType, baseName + "Id", propertiesToReference.Single().ClrType.UnwrapNullableType());

                if (property != null)
                {
                    foreignKeyProperties.Add(property);
                }
            }

            if (foreignKeyProperties.Count < propertiesToReference.Count)
            {
                return(null);
            }

            if (foreignKey.IsRequired == false &&
                foreignKeyProperties.All(p => !((IProperty)p).IsNullable))
            {
                return(null);
            }

            var primaryKey = entityType.FindPrimaryKey();

            if (primaryKey != null)
            {
                if (foreignKeyProperties.All(property => primaryKey.Properties.Contains(property)))
                {
                    return(null);
                }
            }

            return(foreignKeyProperties);
        }
Ejemplo n.º 14
0
        internal void Add(Table table, ForeignKey foreignKey)
        {
            Association fromAssociation = new Association();
            AssociationProperty associationProperty = foreignKey.AssociationProperty;
            if (associationProperty == null)
            {
                // Create the default association property
                associationProperty = new AssociationProperty();
            }

            // Figure out the assocation name
            bool isUnique = false;
            int count = 0;
            while (!isUnique)
            {
                fromAssociation.Name =
                    string.Format(CultureInfo.InvariantCulture, "{0}_{1}{2}",
                    NameHelper.GetTypeName(foreignKey.ToTable),
                    NameHelper.GetTypeName(table),
                    count > 0 ? count.ToString(System.Globalization.CultureInfo.InvariantCulture) : string.Empty);
                isUnique = !names.Contains(fromAssociation.Name);
                count++;
            }
            names.Add(fromAssociation.Name);

            string baseName = GetMemberName(table, foreignKey.ToTable, false);

            // Set FROM table association properties
            if (associationProperty.Parent.Name == null)
            {
                // Automatically create the name
                fromAssociation.Member = baseName;
            }
            else
            {
                fromAssociation.Member = associationProperty.Parent.Name;
                //fromAssociation.Storage = "_" + baseName;
                var members = GetMembersOfTable(table);
                members.Add(fromAssociation.Member);
            }
            //  AccessModifier="Internal"  Modifier="NewVirtual"

            fromAssociation.ThisKey = foreignKey.FromColumnsToString();
            fromAssociation.OtherKey = foreignKey.ToColumnsToString();

            fromAssociation.Type = NameHelper.GetTypeName(foreignKey.ToTable);
            fromAssociation.IsForeignKey = true;
            fromAssociation.AccessModifier = associationProperty.Parent.Access;
            fromAssociation.Modifier = associationProperty.Parent.InheritanceModifier;
            AddAssociation(table.Name, fromTableAssociations, fromAssociation);

            if (associationProperty.Child != null)
            {
                // Create TO table association
                Association toAssociation = new Association();
                toAssociation.Name = fromAssociation.Name;

                baseName = GetMemberName(foreignKey.ToTable, table, true);
                if (associationProperty.Child.Name == null)
                {
                    // Automatically create the name
                    toAssociation.Member = baseName;
                }
                else
                {
                    toAssociation.Member = associationProperty.Child.Name;
                    //toAssociation.Storage = "_" + baseName;
                    var members = GetMembersOfTable(foreignKey.ToTable);
                    members.Add(toAssociation.Member);
                }

                toAssociation.ThisKey = foreignKey.ToColumnsToString();
                toAssociation.OtherKey = foreignKey.FromColumnsToString();

                toAssociation.Type = NameHelper.GetTypeName(table);
                toAssociation.AccessModifier = associationProperty.Child.Access;
                toAssociation.Modifier = associationProperty.Child.InheritanceModifier;
                AddAssociation(foreignKey.ToTable.Name, toTableAssociations, toAssociation);
            }
        }
Ejemplo n.º 15
0
        //----------------------------------------------------------------------------------------------------
        public static string BuildSql__ForeignKey_Create(ForeignKey foreignKey, bool autoFixName, Dictionary <string, string> allConstraints)
        {
            AjaxService.ASPdatabaseService.GetSetVal();
            foreignKey.Validate(Enums.ValidationTypes.Create);

            string optionalSQL_ConstraintName = "";
            string sql_FK_Columns             = "";
            string sql_PK_Columns             = "";
            string sql_DeleteRule             = "";
            string sql_UpdateRule             = "";

            //----------//----------//----------//
            if (autoFixName && allConstraints != null)
            {
                if (String.IsNullOrEmpty(foreignKey.ConstraintName))
                {
                    foreignKey.ConstraintName = String.Format("FK_{0}_{1}", foreignKey.ForeignKey_Schema, foreignKey.ForeignKey_TableName);
                }
                if (allConstraints.ContainsKey(foreignKey.ConstraintName.ToLower()))
                {
                    int loopMax = 10000;
                    for (int i = 1; i < loopMax; i++)
                    {
                        string tryName = foreignKey.ConstraintName + "_" + i.ToString("0000");
                        if (!allConstraints.ContainsKey(tryName.ToLower()))
                        {
                            foreignKey.ConstraintName = tryName;
                            i = loopMax + 1;
                        }
                    }
                }
            }
            //----------//----------//----------//
            if (!String.IsNullOrEmpty(foreignKey.ConstraintName))
            {
                ASPdb.Framework.Validation.ValidateTextForSql1(foreignKey.ConstraintName, true);
                optionalSQL_ConstraintName = "CONSTRAINT " + foreignKey.ConstraintName;
            }
            //----------//----------//----------//
            foreignKey.Columns = (from c in foreignKey.Columns
                                  orderby c.OrdinalPosition
                                  select c).ToArray();
            foreach (var col in foreignKey.Columns)
            {
                if (sql_FK_Columns != "")
                {
                    sql_FK_Columns += ", ";
                    sql_PK_Columns += ", ";
                }
                ASPdb.Framework.Validation.ValidateTextForSql1(col.ForeignKey_ColumnName, true);
                ASPdb.Framework.Validation.ValidateTextForSql1(col.PrimaryKey_ColumnName, true);
                sql_FK_Columns += "[" + col.ForeignKey_ColumnName + "]";
                sql_PK_Columns += "[" + col.PrimaryKey_ColumnName + "]";
            }
            //----------//----------//----------//
            switch (foreignKey.DeleteRule)
            {
            case ForeignKey.E_CascadeOptions.NoAction: sql_DeleteRule = "ON DELETE No Action"; break;

            case ForeignKey.E_CascadeOptions.Cascade: sql_DeleteRule = "ON DELETE Cascade"; break;

            case ForeignKey.E_CascadeOptions.SetDefault: sql_DeleteRule = "ON DELETE Set Default"; break;

            case ForeignKey.E_CascadeOptions.SetNull: sql_DeleteRule = "ON DELETE Set Null"; break;
            }
            //----------//----------//----------//
            switch (foreignKey.UpdateRule)
            {
            case ForeignKey.E_CascadeOptions.NoAction: sql_UpdateRule = "ON UPDATE No Action"; break;

            case ForeignKey.E_CascadeOptions.Cascade: sql_UpdateRule = "ON UPDATE Cascade"; break;

            case ForeignKey.E_CascadeOptions.SetDefault: sql_UpdateRule = "ON UPDATE Set Default"; break;

            case ForeignKey.E_CascadeOptions.SetNull: sql_UpdateRule = "ON UPDATE Set Null"; break;
            }
            //----------//----------//----------//
            //----------//----------//----------//
            string sql = String.Format(@"
                ALTER TABLE [{0}].[{1}]
                ADD
                {2}
                FOREIGN KEY
                ({3})
                REFERENCES [{4}].[{5}]({6})
                {7}
                {8};
            ",
                                       foreignKey.ForeignKey_Schema, foreignKey.ForeignKey_TableName,
                                       optionalSQL_ConstraintName,
                                       sql_FK_Columns,
                                       foreignKey.PrimaryKey_Schema, foreignKey.PrimaryKey_TableName, sql_PK_Columns,
                                       sql_DeleteRule,
                                       sql_UpdateRule);

            return(sql);
        }
 public override ForeignKey AddForeignKey(ForeignKey foreignKey)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 17
0
 public Column(string name, ForeignKey fk)
 {
     Name = name;
     fk.SetHost(this);
 }
Ejemplo n.º 18
0
 public void AddForeignKey(string name, string column, string foreignTable, string foreignColumns, ForeignKeyReference onDelete, ForeignKeyReference onUpdate)
 {
     ForeignKey foreignKey = new ForeignKey(name, column, foreignTable, foreignColumns, onDelete, onUpdate);
     AddForeignKey(foreignKey);
 }
 /// <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 void OnForeignKeyRemoved([NotNull] InternalEntityTypeBuilder entityTypeBuilder, [NotNull] ForeignKey foreignKey)
 => _scope.OnForeignKeyRemoved(
     Check.NotNull(entityTypeBuilder, nameof(entityTypeBuilder)),
     Check.NotNull(foreignKey, nameof(foreignKey)));
Ejemplo n.º 20
0
        private IReadOnlyList <Property> FindMatchingProperties(
            ForeignKey foreignKey, string baseName, bool onDependent, bool matchPK = false)
        {
            var dependentEntityType = onDependent
                ? foreignKey.DeclaringEntityType
                : foreignKey.PrincipalEntityType;
            var principalEntityType = onDependent
                ? foreignKey.PrincipalEntityType
                : foreignKey.DeclaringEntityType;
            var propertiesToReference = onDependent
                ? foreignKey.PrincipalKey.Properties
                : foreignKey.DeclaringEntityType.FindPrimaryKey()?.Properties;

            if (propertiesToReference == null)
            {
                return(null);
            }

            var foreignKeyProperties = new Property[propertiesToReference.Count];
            var matchFound           = true;

            for (var i = 0; i < propertiesToReference.Count; i++)
            {
                var referencedProperty = propertiesToReference[i];
                var property           = TryGetProperty(
                    dependentEntityType,
                    baseName, referencedProperty.Name);

                if (property == null)
                {
                    matchFound = false;
                    continue;
                }

                foreignKeyProperties[i] = property;
            }

            if (!matchFound &&
                propertiesToReference.Count == 1)
            {
                var property = TryGetProperty(
                    dependentEntityType,
                    baseName, "Id");

                if (property != null)
                {
                    foreignKeyProperties[0] = property;
                    matchFound = true;
                }
            }

            if (!matchFound)
            {
                return(null);
            }

            if (!ForeignKey.AreCompatible(
                    propertiesToReference,
                    foreignKeyProperties,
                    principalEntityType,
                    dependentEntityType,
                    false))
            {
                _logger.IncompatibleMatchingForeignKeyProperties(foreignKeyProperties, propertiesToReference);
                return(new Property[0]);
            }

            foreach (var key in dependentEntityType.GetKeys())
            {
                if (key.Properties.All(property => foreignKeyProperties.Contains(property)) &&
                    (!foreignKey.IsUnique ||
                     (key.IsPrimaryKey() && !matchPK)))
                {
                    return(new Property[0]);
                }
            }

            return(foreignKeyProperties);
        }
Ejemplo n.º 21
0
 protected override bool IsForeignKeyExist(ForeignKey foreignKey)
 {
     return(IsForeignKeyExist(foreignKey.Entity.GetNameInStore(), foreignKey.ForeignEntityInfo.GetNameInStore()));
 }
Ejemplo n.º 22
0
 public override string CreateForeignKey(ForeignKey foreignKey)
 {
     return(string.Empty); // Not supported yet - needs to drop and recreate tables etc
 }
Ejemplo n.º 23
0
        public static IServiceCollection AddNHibernate(this IServiceCollection services, string cnString)
        {
            var sessionFactory = Fluently.Configure()
                                 .Database(MsSqlConfiguration.MsSql2008.ConnectionString(cnString))
                                 .Mappings(m => m.FluentMappings.AddFromAssemblyOf <OrderMap>().Conventions.Add(ForeignKey.EndsWith("Id")))
                                 .BuildSessionFactory();

            services.AddSingleton <ISessionFactory>(sessionFactory);

            services.AddSingleton <IUnitOfWorkProvider, UnitOfWorkProvider>();

            return(services);
        }
Ejemplo n.º 24
0
 public override string DropForeignKey(ForeignKey foreignKey)
 {
     throw new System.NotImplementedException();
 }
Ejemplo n.º 25
0
 public void AddForeignKey(ForeignKey foreignKey)
 {
     if (ForeignKeys == null) ForeignKeys = new ForeignKeyList();
     if (foreignKey.Name == null)
     {
         foreignKey.Name = @"FK_";
         foreignKey.Name += Name + @"_";
         foreignKey.Name += foreignKey.ForeignTable + @"_";
         for (int idx = 0; idx < foreignKey.Columns.Length; idx++)
         {
             if (idx > 0) foreignKey.Name += @"_";
             foreignKey.Name += foreignKey.Columns[idx];
         }
     }
     ForeignKeys.Add(foreignKey);
 }
Ejemplo n.º 26
0
        internal void PopulateArray(DataTable dataTableFk, DataTable dataTablePk)
        {
            DataTable metaData = new DataTable();

            metaData.Columns.AddRange(
                new DataColumn[] {
                new DataColumn("PK_TABLE_CATALOG"),
                new DataColumn("PK_TABLE_SCHEMA"),
                new DataColumn("PK_TABLE_NAME"),
                new DataColumn("FK_TABLE_CATALOG"),
                new DataColumn("FK_TABLE_SCHEMA"),
                new DataColumn("FK_TABLE_NAME"),
                new DataColumn("ORDINAL"),
                new DataColumn("PK_NAME"),
                new DataColumn("FK_NAME"),
                new DataColumn("UPDATE_RULE"),
                new DataColumn("DELETE_RULE"),
                new DataColumn("DEFERRABILITY")
            }
                );
            this.BindToColumns(metaData);

            ForeignKey key = null;

            int j = 0;

            for (int i = 0; i < dataTableFk.Rows.Count; i++)
            {
                DataRow rowPk = dataTablePk.Rows[i];
                DataRow rowFk = dataTableFk.Rows[i];
                try
                {
                    string pkschema  = rowPk["TABLE_SCHEMA"].ToString();
                    string pktable   = rowPk["TABLE_NAME"].ToString();
                    string pkcolumn  = rowPk["COLUMN_NAME"].ToString();
                    string fkschema  = rowPk["TABLE_SCHEMA"].ToString();
                    string fktable   = rowFk["TABLE_NAME"].ToString();
                    string fkcolumn  = rowFk["COLUMN_NAME"].ToString();
                    string fkKeyName = rowFk["CONSTRAINT_NAME"].ToString();
                    string pkKeyName = rowFk["PK_CONSTRAINT_NAME"].ToString();

                    //DataRow row = rowView.Row;
                    key = this.GetByName(fkKeyName);

                    if (null == key)
                    {
                        DataRow row = metaData.NewRow();

                        row["PK_TABLE_CATALOG"] = pkschema;
                        row["PK_TABLE_SCHEMA"]  = pkschema;
                        row["PK_TABLE_NAME"]    = pktable;
                        row["FK_TABLE_CATALOG"] = fkschema;
                        row["FK_TABLE_SCHEMA"]  = fkschema;
                        row["FK_TABLE_NAME"]    = fktable;
                        row["ORDINAL"]          = j++.ToString();
                        row["PK_NAME"]          = pkKeyName;
                        row["FK_NAME"]          = fkKeyName;
                        row["UPDATE_RULE"]      = "";
                        row["DELETE_RULE"]      = "";
                        row["DEFERRABILITY"]    = 0;

                        metaData.Rows.Add(row);

                        key             = (ForeignKey)this.dbRoot.ClassFactory.CreateForeignKey();
                        key.dbRoot      = this.dbRoot;
                        key.ForeignKeys = this;
                        key.Row         = row;
                        this._array.Add(key);
                    }

                    key.AddForeignColumn(pkschema, pkschema, pktable, pkcolumn, true);
                    key.AddForeignColumn(fkschema, fkschema, fktable, fkcolumn, false);
                }
                catch (Exception ex)
                {
                    string tmp = ex.Message;
                }
            }
        }
Ejemplo n.º 27
0
        public void Setting_IsRequired_to_false_will_set_all_FK_properties_as_nullable()
        {
            var entityType = new Model().AddEntityType("E");
            var property = entityType.AddProperty("Id1", typeof(int));
            var property1 = entityType.AddProperty("Id2", typeof(string));
            entityType.GetOrSetPrimaryKey(new[]
                {
                    property,
                    property1
                });

            var dependentProp1 = entityType.AddProperty("P1", typeof(int?));
            var dependentProp2 = entityType.AddProperty("P2", typeof(string));

            var foreignKey = new ForeignKey(new[] { dependentProp1, dependentProp2 }, entityType.GetPrimaryKey(), entityType, entityType) { IsRequired = false };

            Assert.False(foreignKey.IsRequired.Value);
            Assert.True(dependentProp1.IsNullable.Value);
            Assert.True(dependentProp2.IsNullable.Value);
        }
Ejemplo n.º 28
0
            public List <String> GetForeignKeys(Schema s)
            {
                var h = new HashSet <ForeignKey>();

                var l = new List <String>();

                foreach (var t in s.Types)
                {
                    if (t.OnEntity)
                    {
                        foreach (var f in t.Entity.Fields)
                        {
                            if (f.Attribute.OnNavigation)
                            {
                                if (!f.Attribute.Navigation.IsUnique)
                                {
                                    continue;
                                }

                                if (f.Attribute.Navigation.IsReverse)
                                {
                                    EntityDef ThisTable = null;
                                    if (f.Type.OnTypeRef)
                                    {
                                        ThisTable = Records[f.Type.TypeRef.Value];
                                    }
                                    else if (f.Type.OnOptional)
                                    {
                                        ThisTable = Records[f.Type.Optional.Value];
                                    }
                                    else if (f.Type.OnList)
                                    {
                                        ThisTable = Records[f.Type.List.Value];
                                    }
                                    else
                                    {
                                        throw new InvalidOperationException();
                                    }
                                    var fk = new ForeignKey {
                                        ThisTableName = ThisTable.CollectionName, ThisKeyColumns = f.Attribute.Navigation.OtherKey, OtherTableName = t.Entity.CollectionName, OtherKeyColumns = f.Attribute.Navigation.ThisKey
                                    };
                                    if (!h.Contains(fk))
                                    {
                                        var Name = fk.GetLimitedName(MaxNameLength);
                                        l.AddRange(GetForeignKey(Name, fk.ThisTableName, fk.ThisKeyColumns, fk.OtherTableName, fk.OtherKeyColumns));
                                        h.Add(fk);
                                    }
                                }
                                else
                                {
                                    var fk = new ForeignKey {
                                        ThisTableName = t.Entity.CollectionName, ThisKeyColumns = f.Attribute.Navigation.ThisKey, OtherTableName = Records[f.Type.TypeRef.Value].CollectionName, OtherKeyColumns = f.Attribute.Navigation.OtherKey
                                    };
                                    if (!h.Contains(fk))
                                    {
                                        var Name = fk.GetLimitedName(MaxNameLength);
                                        l.AddRange(GetForeignKey(Name, fk.ThisTableName, fk.ThisKeyColumns, fk.OtherTableName, fk.OtherKeyColumns));
                                        h.Add(fk);
                                    }
                                }
                            }
                        }
                    }
                }
                return(l);
            }
Ejemplo n.º 29
0
 /// <summary>
 /// There are no comments for TableForeignKeys in the schema.
 /// </summary>
 public void AddToTableForeignKeys(ForeignKey foreignKey)
 {
   base.AddObject("TableForeignKeys", foreignKey);
 }
Ejemplo n.º 30
0
    public void IdentifyMappingTable(List <ForeignKey> fkList, Tables tables, bool checkForFkNameClashes)
    {
        IsMapping = false;

        var nonReadOnlyColumns = Columns.Where(c => !c.IsIdentity && !c.IsRowVersion && !c.IsStoreGenerated && !c.Hidden).ToList();

        // Ignoring read-only columns, it must have only 2 columns to be a mapping table
        if (nonReadOnlyColumns.Count != 2)
        {
            return;
        }

        // Must have 2 primary keys
        if (nonReadOnlyColumns.Count(x => x.IsPrimaryKey) != 2)
        {
            return;
        }

        // No columns should be nullable
        if (nonReadOnlyColumns.Any(x => x.IsNullable))
        {
            return;
        }

        // Find the foreign keys for this table
        var foreignKeys = fkList.Where(x =>
                                       string.Compare(x.FkTableName, Name, StringComparison.OrdinalIgnoreCase) == 0 &&
                                       string.Compare(x.FkSchema, Schema, StringComparison.OrdinalIgnoreCase) == 0)
                          .ToList();

        // Each column must have a foreign key, therefore check column and foreign key counts match
        if (foreignKeys.Select(x => x.FkColumn).Distinct().Count() != 2)
        {
            return;
        }

        ForeignKey left  = foreignKeys[0];
        ForeignKey right = foreignKeys[1];

        if (!left.IncludeReverseNavigation || !right.IncludeReverseNavigation)
        {
            return;
        }

        Table leftTable = tables.GetTable(left.PkTableName, left.PkSchema);

        if (leftTable == null)
        {
            return;
        }

        Table rightTable = tables.GetTable(right.PkTableName, right.PkSchema);

        if (rightTable == null)
        {
            return;
        }

        var leftPropName = leftTable.GetUniqueColumnName(rightTable.NameHumanCase, right, checkForFkNameClashes, false, Relationship.ManyToOne);     // relationship from the mapping table to each side is Many-to-One

        leftPropName = Settings.MappingTableRename(Name, leftTable.NameHumanCase, leftPropName);
        var rightPropName = rightTable.GetUniqueColumnName(leftTable.NameHumanCase, left, checkForFkNameClashes, false, Relationship.ManyToOne);     // relationship from the mapping table to each side is Many-to-One

        rightPropName = Settings.MappingTableRename(Name, rightTable.NameHumanCase, rightPropName);
        leftTable.AddMappingConfiguration(left, right, leftPropName, rightPropName);

        IsMapping = true;
        rightTable.AddReverseNavigation(Relationship.ManyToMany, rightTable.NameHumanCase, leftTable, rightPropName, null, null, this);
        leftTable.AddReverseNavigation(Relationship.ManyToMany, leftTable.NameHumanCase, rightTable, leftPropName, null, null, this);
    }
Ejemplo n.º 31
0
        /// <summary>
        /// Deserialzes the provided binary data of the object. This is the full data block which follows the data
        /// signature and data block length.
        /// </summary>
        /// <param name="inData">The binary data containing the object.</param>
        public void LoadBinaryData(byte[] inData)
        {
            using (MemoryStream ms = new MemoryStream(inData))
            {
                using (BinaryReader br = new BinaryReader(ms))
                {
                    this.GroupNameOffset            = br.ReadUInt32();
                    this.DescriptiveGroupNameOffset = br.ReadUInt32();

                    this.Flags = (GroupFlags)br.ReadUInt32();

                    this.BoundingBox = br.ReadBox();

                    this.PortalReferenceStartingIndex = br.ReadUInt16();
                    this.PortalReferenceCount         = br.ReadUInt16();

                    this.RenderBatchCountA        = br.ReadUInt16();
                    this.RenderBatchCountInterior = br.ReadUInt16();
                    this.RenderBatchCountExterior = br.ReadUInt16();
                    this.Unknown = br.ReadUInt16();

                    for (int i = 0; i < 4; ++i)
                    {
                        this.FogIndices.Add(br.ReadByte());
                    }

                    this.LiquidType = br.ReadUInt32();
                    this.GroupID    = new ForeignKey <uint>(DatabaseName.WMOAreaTable, nameof(WMOAreaTableRecord.WMOGroupID), br.ReadUInt32());

                    this.UnknownFlags = br.ReadUInt32();
                    this.Unused       = br.ReadUInt32();

                    // Required subchunks
                    this.PolygonMaterials   = br.ReadIFFChunk <ModelPolygonMaterials>();
                    this.VertexIndices      = br.ReadIFFChunk <ModelVertexIndices>();
                    this.Vertices           = br.ReadIFFChunk <ModelVertices>();
                    this.Normals            = br.ReadIFFChunk <ModelNormals>();
                    this.TextureCoordinates = br.ReadIFFChunk <ModelTextureCoordinates>();
                    this.RenderBatches      = br.ReadIFFChunk <ModelRenderBatches>();

                    // Optional chunks
                    if (br.PeekChunkSignature() == MOBS.Signature)
                    {
                        this.mobs = br.ReadIFFChunk <MOBS>();
                    }

                    if (this.Flags.HasFlag(GroupFlags.HasLights))
                    {
                        this.LightReferences = br.ReadIFFChunk <ModelLightReferences>();
                    }

                    if (this.Flags.HasFlag(GroupFlags.HasDoodads))
                    {
                        this.DoodadReferences = br.ReadIFFChunk <ModelDoodadReferences>();
                    }

                    if (this.Flags.HasFlag(GroupFlags.HasBSP))
                    {
                        this.BSPNodes       = br.ReadIFFChunk <ModelBSPNodes>();
                        this.BSPFaceIndices = br.ReadIFFChunk <ModelBSPFaceIndices>();
                    }

                    if (this.Flags.HasFlag(GroupFlags.UnknownLODRelated))
                    {
                        this.mpbv = br.ReadIFFChunk <MPBV>();
                        this.mpbp = br.ReadIFFChunk <MPBP>();
                        this.mpbi = br.ReadIFFChunk <MPBI>();
                        this.mpbg = br.ReadIFFChunk <MPBG>();
                    }

                    if (this.Flags.HasFlag(GroupFlags.HasVertexColours))
                    {
                        this.VertexColours = br.ReadIFFChunk <ModelVertexColours>();
                    }

                    if (this.Flags.HasFlag(GroupFlags.HasLiquids))
                    {
                        this.Liquids = br.ReadIFFChunk <ModelLiquids>();
                    }

                    if (this.Flags.HasFlag(GroupFlags.HasTriangleStrips))
                    {
                        this.TriangleStripIndices = br.ReadIFFChunk <ModelTriangleStripIndices>();
                        this.TriangleStrips       = br.ReadIFFChunk <ModelTriangleStrips>();
                    }

                    if (this.Flags.HasFlag(GroupFlags.HasTwoTextureCoordinateSets))
                    {
                        this.AdditionalTextureCoordinates = br.ReadIFFChunk <ModelTextureCoordinates>();
                    }

                    if (this.Flags.HasFlag(GroupFlags.HasTwoVertexShadingSets))
                    {
                        this.AdditionalVertexColours = br.ReadIFFChunk <ModelVertexColours>();
                    }

                    if (this.Flags.HasFlag(GroupFlags.HasThreeTextureCoordinateSets))
                    {
                        this.SecondAddtionalTextureCoordinates = br.ReadIFFChunk <ModelTextureCoordinates>();
                    }
                }
            }
        }
Ejemplo n.º 32
0
    public string GetUniqueColumnName(string tableNameHumanCase, ForeignKey foreignKey, bool checkForFkNameClashes, bool makeSingular, Relationship relationship)
    {
        var addReverseNavigationUniquePropName = (checkForFkNameClashes || Name == foreignKey.FkTableName || (Name == foreignKey.PkTableName && foreignKey.IncludeReverseNavigation));

        if (ReverseNavigationUniquePropName.Count == 0)
        {
            ReverseNavigationUniquePropName.Add(NameHumanCase);
            ReverseNavigationUniquePropName.AddRange(Columns.Select(c => c.NameHumanCase));
        }

        if (!makeSingular)
        {
            tableNameHumanCase = Inflector.MakePlural(tableNameHumanCase);
        }

        if (checkForFkNameClashes && ReverseNavigationUniquePropName.Contains(tableNameHumanCase) && !ReverseNavigationUniquePropNameClashes.Contains(tableNameHumanCase))
        {
            ReverseNavigationUniquePropNameClashes.Add(tableNameHumanCase);     // Name clash
        }
        // Attempt 1
        string fkName = (Settings.UsePascalCase ? Inflector.ToTitleCase(foreignKey.FkColumn) : foreignKey.FkColumn).Replace(" ", "").Replace("$", "");
        string name   = Settings.ForeignKeyName(tableNameHumanCase, foreignKey, fkName, relationship, 1);
        string col;

        if (!ReverseNavigationUniquePropNameClashes.Contains(name) && !ReverseNavigationUniquePropName.Contains(name))
        {
            if (addReverseNavigationUniquePropName)
            {
                ReverseNavigationUniquePropName.Add(name);
            }

            return(name);
        }

        if (Name == foreignKey.FkTableName)
        {
            // Attempt 2
            if (fkName.ToLowerInvariant().EndsWith("id"))
            {
                col = Settings.ForeignKeyName(tableNameHumanCase, foreignKey, fkName, relationship, 2);
                if (checkForFkNameClashes && ReverseNavigationUniquePropName.Contains(col) &&
                    !ReverseNavigationUniquePropNameClashes.Contains(col))
                {
                    ReverseNavigationUniquePropNameClashes.Add(col);     // Name clash
                }
                if (!ReverseNavigationUniquePropNameClashes.Contains(col) &&
                    !ReverseNavigationUniquePropName.Contains(col))
                {
                    if (addReverseNavigationUniquePropName)
                    {
                        ReverseNavigationUniquePropName.Add(col);
                    }

                    return(col);
                }
            }

            // Attempt 3
            col = Settings.ForeignKeyName(tableNameHumanCase, foreignKey, fkName, relationship, 3);
            if (checkForFkNameClashes && ReverseNavigationUniquePropName.Contains(col) &&
                !ReverseNavigationUniquePropNameClashes.Contains(col))
            {
                ReverseNavigationUniquePropNameClashes.Add(col);     // Name clash
            }
            if (!ReverseNavigationUniquePropNameClashes.Contains(col) &&
                !ReverseNavigationUniquePropName.Contains(col))
            {
                if (addReverseNavigationUniquePropName)
                {
                    ReverseNavigationUniquePropName.Add(col);
                }

                return(col);
            }
        }

        // Attempt 4
        col = Settings.ForeignKeyName(tableNameHumanCase, foreignKey, fkName, relationship, 4);
        if (checkForFkNameClashes && ReverseNavigationUniquePropName.Contains(col) && !ReverseNavigationUniquePropNameClashes.Contains(col))
        {
            ReverseNavigationUniquePropNameClashes.Add(col);     // Name clash
        }
        if (!ReverseNavigationUniquePropNameClashes.Contains(col) && !ReverseNavigationUniquePropName.Contains(col))
        {
            if (addReverseNavigationUniquePropName)
            {
                ReverseNavigationUniquePropName.Add(col);
            }

            return(col);
        }

        // Attempt 5
        for (int n = 1; n < 99; ++n)
        {
            col = Settings.ForeignKeyName(tableNameHumanCase, foreignKey, fkName, relationship, 5) + n;

            if (ReverseNavigationUniquePropName.Contains(col))
            {
                continue;
            }

            if (addReverseNavigationUniquePropName)
            {
                ReverseNavigationUniquePropName.Add(col);
            }

            return(col);
        }

        // Give up
        return(Settings.ForeignKeyName(tableNameHumanCase, foreignKey, fkName, relationship, 6));
    }
Ejemplo n.º 33
0
 public ForeignKey GetRefTableForeignKey(ForeignKey foreignKey, string referencedColumn)
 {
     return foreignKey.Parent.Parent.Tables[foreignKey.ReferencedTable].ForeignKeys.OfType<ForeignKey>().Where(
         key => key.ReferencedTable == foreignKey.Parent.Name&&key.Columns.OfType<ForeignKeyColumn>().Any(column => column.ReferencedColumn==referencedColumn)).FirstOrDefault();
 }
        public void OnForeignKeyRemoved_calls_apply_on_conventions_in_order()
        {
            var conventions = new ConventionSet();

            var foreignKeyRemoved = false;

            var convention = new Mock<IForeignKeyRemovedConvention>();
            convention.Setup(c => c.Apply(It.IsAny<InternalEntityTypeBuilder>(), It.IsAny<ForeignKey>())).Callback(() => foreignKeyRemoved = true);
            conventions.ForeignKeyRemovedConventions.Add(convention.Object);

            var builder = new InternalModelBuilder(new Model(), conventions);

            var entityBuilder = builder.Entity(typeof(Order), ConfigurationSource.Convention);
            var foreignKey = new ForeignKey(
                new[] { entityBuilder.Property("FK", typeof(int), ConfigurationSource.Convention).Metadata },
                entityBuilder.HasKey(new[] { "OrderId" }, ConfigurationSource.Convention).Metadata,
                entityBuilder.Metadata,
                entityBuilder.Metadata);
            var conventionDispatcher = new ConventionDispatcher(conventions);
            conventionDispatcher.OnForeignKeyRemoved(entityBuilder, foreignKey);

            Assert.True(foreignKeyRemoved);
        }
 public DB2ForeignKeyTransformer(ForeignKey foreignKey, UTF_EA.AssociationEnd associationEnd, NameTranslator nameTranslator) : base(foreignKey, associationEnd, nameTranslator)
 {
 }
Ejemplo n.º 36
0
 public static RelationalForeignKeyAnnotations Relational([NotNull] this ForeignKey foreignKey)
 => new RelationalForeignKeyAnnotations(Check.NotNull(foreignKey, nameof(foreignKey)));
Ejemplo n.º 37
0
 protected override void CreateForeignKey(ForeignKey foreignKey)
 {
     // Not supported by sqlite
     // https://www.sqlite.org/omitted.html
 }
Ejemplo n.º 38
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 void Apply(InternalEntityTypeBuilder entityTypeBuilder, ForeignKey foreignKey)
 => SetKeyValueGeneration(foreignKey.Properties, entityTypeBuilder.Metadata);
Ejemplo n.º 39
0
        public static NpgsqlForeignKeyAnnotations Npgsql([NotNull] this ForeignKey foreignKey)
        {
            Check.NotNull(foreignKey, nameof(foreignKey));

            return(new NpgsqlForeignKeyAnnotations(foreignKey));
        }
Ejemplo n.º 40
0
        public static NpgsqlForeignKeyExtensions Npgsql([NotNull] this ForeignKey foreignKey)
        {
            Check.NotNull(foreignKey, "foreignKey");

            return(new NpgsqlForeignKeyExtensions(foreignKey));
        }
Ejemplo n.º 41
0
        public static List <Database> GetAllData()
        {
            List <Database> databases = new List <Database>();
            XmlDocument     xmlDoc    = new XmlDocument();

            xmlDoc.Load(filePath);
            XmlNodeList nodelistDB = xmlDoc.DocumentElement.SelectNodes("/Databases/DataBase");

            if (nodelistDB != null)
            {
                foreach (XmlNode nodeDB in nodelistDB)
                {
                    Database database     = new Database();
                    XmlNode  DatabaseName = nodeDB.Attributes.GetNamedItem("dataBaseName");
                    if (DatabaseName != null)
                    {
                        database.DatabaseName = DatabaseName.Value;
                    }
                    XmlNodeList  nodelistTB = xmlDoc.DocumentElement.SelectNodes("/Databases/DataBase/Tables/Table");
                    List <Table> tablesList = new List <Table>();
                    foreach (XmlNode nodeTB in nodelistTB)
                    {
                        if (nodeTB != null && nodeTB.ParentNode.ParentNode == nodeDB)
                        {
                            Table   table     = new Table();
                            XmlNode tablename = nodeTB.Attributes.GetNamedItem("tableName");
                            if (tablename != null)
                            {
                                table.TableName = tablename.Value;
                            }
                            XmlNode fileName = nodeTB.Attributes.GetNamedItem("fileName");
                            if (fileName != null)
                            {
                                table.FileName = fileName.Value;
                            }
                            XmlNode rowLength = nodeTB.Attributes.GetNamedItem("rowLength");
                            if (rowLength != null)
                            {
                                table.RowLength = int.Parse(rowLength.Value);
                            }
                            XmlNodeList   nodeListCo  = xmlDoc.DocumentElement.SelectNodes("/Databases/DataBase/Tables/Table/Structure/Attribute");
                            List <Column> columnsList = new List <Column>();
                            foreach (XmlNode nodeCo in nodeListCo)
                            {
                                if (nodeCo != null && nodeCo.ParentNode.ParentNode == nodeTB)
                                {
                                    Column  column     = new Column();
                                    XmlNode ColumnName = nodeCo.Attributes.GetNamedItem("attributeName");
                                    if (ColumnName != null)
                                    {
                                        column.ColumnName = ColumnName.Value;
                                    }
                                    XmlNode Type = nodeCo.Attributes.GetNamedItem("type");
                                    if (Type != null)
                                    {
                                        column.Type = Type.Value;
                                    }
                                    XmlNode Length = nodeCo.Attributes.GetNamedItem("length");
                                    if (Type != null)
                                    {
                                        column.Length = int.Parse(Length.Value);
                                    }
                                    XmlNode isnull = nodeCo.Attributes.GetNamedItem("isnull");
                                    if (Type != null)
                                    {
                                        column.IsNull = Utilities.GetBoolValueFromString(isnull.Value);
                                    }
                                    columnsList.Add(column);
                                }
                            }
                            table.Columns = columnsList;

                            XmlNodeList nodeListPK = xmlDoc.DocumentElement.SelectNodes("/Databases/DataBase/Tables/Table/primaryKey/pkAttribute");
                            if (nodeListPK != null)
                            {
                                List <PrimaryKey> primaryKeysList = new List <PrimaryKey>();
                                foreach (XmlNode nodePK in nodeListPK)
                                {
                                    if (nodePK != null && nodePK.ParentNode.ParentNode == nodeTB)
                                    {
                                        PrimaryKey primaryKey = new PrimaryKey();
                                        primaryKey.Key = nodePK.InnerText;
                                        primaryKeysList.Add(primaryKey);
                                    }
                                }
                                table.PrimaryKey = primaryKeysList;
                            }
                            XmlNodeList nodeListUK = xmlDoc.DocumentElement.SelectNodes("/Databases/DataBase/Tables/Table/uniqueKeys/UniqueAttribute");
                            if (nodeListUK.Count > 0)
                            {
                                List <UniqueKey> uniqueKeysList = new List <UniqueKey>();
                                foreach (XmlNode nodeUK in nodeListUK)
                                {
                                    if (nodeUK != null && nodeUK.ParentNode.ParentNode == nodeTB)
                                    {
                                        UniqueKey uniqueKey = new UniqueKey();
                                        uniqueKey.Key = nodeUK.InnerText;
                                        uniqueKeysList.Add(uniqueKey);
                                    }
                                }
                                table.UniqueKey = uniqueKeysList;
                            }
                            XmlNodeList nodeListIF = xmlDoc.DocumentElement.SelectNodes("/Databases/DataBase/Tables/Table/IndexFiles/IndexFile");
                            if (nodeListIF.Count > 0)
                            {
                                List <IndexFile> indexfilelist = new List <IndexFile>();
                                foreach (XmlNode nodeIF in nodeListIF)
                                {
                                    if (nodeIF != null && nodeIF.ParentNode.ParentNode == nodeTB)
                                    {
                                        IndexFile indexfile = new IndexFile();
                                        XmlNode   IndexName = nodeIF.Attributes.GetNamedItem("indexName");
                                        if (IndexName != null)
                                        {
                                            indexfile.IndexName = IndexName.Value;
                                        }
                                        XmlNode KeyLength = nodeIF.Attributes.GetNamedItem("keyLength");
                                        if (KeyLength != null)
                                        {
                                            indexfile.KeyLength = int.Parse(KeyLength.Value);
                                        }
                                        XmlNode IsUnique = nodeIF.Attributes.GetNamedItem("isUnique");
                                        if (IsUnique != null)
                                        {
                                            indexfile.IsUnique = Utilities.GetBoolValueFromString(IsUnique.Value);
                                        }
                                        XmlNode IndexType = nodeIF.Attributes.GetNamedItem("indexType");
                                        if (IndexType != null)
                                        {
                                            indexfile.IndexType = IndexType.Value;
                                        }
                                        XmlNode IndexAttributeNode = nodeIF.FirstChild.FirstChild;
                                        if (IndexAttributeNode.Name == "IAttribute" && IndexAttributeNode.InnerText != "")
                                        {
                                            indexfile.IndexAttribute = IndexAttributeNode.InnerText;
                                        }
                                        indexfilelist.Add(indexfile);
                                    }
                                }
                                table.IndexFile = indexfilelist;
                            }

                            XmlNodeList nodeListFK = xmlDoc.DocumentElement.SelectNodes("/Databases/DataBase/Tables/Table/foreignKeys/foreignKey");
                            if (nodeListFK.Count > 0)
                            {
                                List <ForeignKey> FKlist = new List <ForeignKey>();
                                foreach (XmlNode nodeFK in nodeListFK)
                                {
                                    if (nodeFK.ParentNode.ParentNode == nodeTB)
                                    {
                                        ForeignKey fk = new ForeignKey();
                                        fk.Key = nodeFK.FirstChild.InnerText;
                                        XmlNode nodeFKRef = nodeFK.LastChild;
                                        fk.RefTable     = nodeFKRef.FirstChild.InnerText;
                                        fk.RefAttribute = nodeFKRef.LastChild.InnerText;
                                        FKlist.Add(fk);
                                    }
                                }
                                table.ForeignKey = FKlist;
                            }
                            tablesList.Add(table);
                        }
                    }
                    database.Tables = tablesList;
                    databases.Add(database);
                }
            }
            return(databases);
        }
Ejemplo n.º 42
0
 protected static void AddForeignKeyColumn(ForeignKey foreignKey, string name, string refColumnName)
 {
     var foreignKeyColumn = Isolate.Fake.Instance<ForeignKeyColumn>();
     Isolate.WhenCalled(() => foreignKeyColumn.ReferencedColumn).WillReturn(refColumnName);
     Isolate.WhenCalled(() => foreignKeyColumn.Name).WillReturn(name);
     if (foreignKey.Columns.Count==0)
         Isolate.WhenCalled(() => foreignKey.Columns).WillReturnCollectionValuesOf(new List<ForeignKeyColumn> { foreignKeyColumn });
     else {
         foreignKey.Columns.Add(foreignKeyColumn);
     }
 }
Ejemplo n.º 43
0
        public void DropParentShouldDropFKs()
        {
            ForeignKey getForeignKey(Table table, string fkColumn, Table parentTable, string parentColumn)
            {
                var fk = new ForeignKey()
                {
                    Parent          = table,
                    Name            = $"FK_{table.Name}_{fkColumn}",
                    ReferencedTable = parentTable,
                    Columns         = new ForeignKey.Column[]
                    {
                        new ForeignKey.Column()
                        {
                            ReferencingName = fkColumn, ReferencedName = parentColumn
                        }
                    }
                };

                return(fk);
            };

            var parentTbl = ModelBuilder.BuildTable("parent", "this", "that", "other", "Id");
            var child1    = ModelBuilder.BuildTable("child1", "parentId", "hello", "whatever", "chunga");
            var child2    = ModelBuilder.BuildTable("child2", "parentId", "yowza", "plimza", "faruga");

            var srcModel = new DataModel()
            {
                Tables      = new Table[] { child1, child2 },
                ForeignKeys = new ForeignKey[]
                {
                    getForeignKey(child1, "parentId", parentTbl, "Id"),
                    getForeignKey(child2, "parentId", parentTbl, "Id")
                }
            };

            var destModel = new DataModel()
            {
                Tables      = new Table[] { parentTbl, child1, child2 },
                ForeignKeys = new ForeignKey[]
                {
                    getForeignKey(child1, "parentId", parentTbl, "Id"),
                    getForeignKey(child2, "parentId", parentTbl, "Id")
                }
            };

            var diff = DataModel.Compare(srcModel, destModel);

            Assert.IsTrue(diff.Contains(new ScriptAction()
            {
                Type     = ActionType.Drop,
                Object   = parentTbl,
                Commands = new string[]
                {
                    "ALTER TABLE <child1> DROP CONSTRAINT <FK_child1_parentId>",
                    "ALTER TABLE <child2> DROP CONSTRAINT <FK_child2_parentId>",
                    "DROP TABLE <parent>"
                }
            }));

            var script = new SqlServerDialect().FormatScript(diff);

            Debug.Write(script);
        }
Ejemplo n.º 44
0
        public void IsRequired_true_when_dependent_property_not_nullable()
        {
            var entityType = new Model().AddEntityType("E");
            entityType.GetOrSetPrimaryKey(entityType.GetOrAddProperty("Id", typeof(int), shadowProperty: true));
            var dependentProp = entityType.GetOrAddProperty("P", typeof(int), shadowProperty: true);
            dependentProp.IsNullable = false;

            var foreignKey = new ForeignKey(new[] { dependentProp }, entityType.GetPrimaryKey(), entityType);

            Assert.Null(foreignKey.IsRequired);
            Assert.True(((IForeignKey)foreignKey).IsRequired);
        }
Ejemplo n.º 45
0
        protected override IEnumerable<IDataParameter> CoreGetForeignKeyColumnParameters(IUnitOfWorkContext unitOfWorkContext, string dataSourceTag, Database database, Schema schema, Table table, ForeignKey foreignKey)
        {
            if ((object)unitOfWorkContext == null)
                throw new ArgumentNullException("unitOfWorkContext");

            if ((object)dataSourceTag == null)
                throw new ArgumentNullException("dataSourceTag");

            if ((object)database == null)
                throw new ArgumentNullException("database");

            if ((object)schema == null)
                throw new ArgumentNullException("schema");

            if ((object)table == null)
                throw new ArgumentNullException("table");

            if ((object)foreignKey == null)
                throw new ArgumentNullException("foreignKey");

            if (dataSourceTag.SafeToString().ToLower() == "odbc.sqlserver")
            {
                return new IDataParameter[]
                       {
                           unitOfWorkContext.CreateParameter(ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P1", schema.SchemaName),
                           unitOfWorkContext.CreateParameter(ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P2", table.TableName),
                           unitOfWorkContext.CreateParameter(ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P3", foreignKey.ForeignKeyName)
                       };
            }
            else if (dataSourceTag.SafeToString().ToLower() == "odbc.sybaseiq")
            {
                return new IDataParameter[]
                       {
                           unitOfWorkContext.CreateParameter(ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P1", schema.SchemaName),
                           unitOfWorkContext.CreateParameter(ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P2", table.TableName),
                           unitOfWorkContext.CreateParameter(ParameterDirection.Input, DbType.String, 100, 0, 0, true, "@P3", foreignKey.ForeignKeyName)
                       };
            }

            throw new ArgumentOutOfRangeException(string.Format("dataSourceTag: '{0}'", dataSourceTag));
        }
Ejemplo n.º 46
0
        public void Can_create_foreign_key_with_non_pk_principal()
        {
            var entityType = new Model().AddEntityType("E");
            var keyProp = entityType.GetOrAddProperty("Id", typeof(int), shadowProperty: true);
            var dependentProp = entityType.GetOrAddProperty("P", typeof(int), shadowProperty: true);
            var principalProp = entityType.GetOrAddProperty("U", typeof(int), shadowProperty: true);
            entityType.GetOrSetPrimaryKey(keyProp);
            var principalKey = entityType.AddKey(principalProp);

            var foreignKey
                = new ForeignKey(new[] { dependentProp }, principalKey, entityType)
                {
                    IsUnique = false
                };

            Assert.Same(entityType, foreignKey.PrincipalEntityType);
            Assert.Same(principalProp, foreignKey.PrincipalKey.Properties.Single());
            Assert.Same(dependentProp, foreignKey.Properties.Single());
            Assert.False(foreignKey.IsUnique.Value);
            Assert.Same(principalKey, foreignKey.PrincipalKey);
        }
Ejemplo n.º 47
0
        /// <summary>
        /// Создаём таблицу из схемы модуля
        /// </summary>
        /// <param name="module">Метаданные модуля</param>
        public void CreateTableFromModuleSchema(ModuleMetadata module)
        {
            if (!_database.Tables.Contains(module.ModuleName))
            {
                try
                {
                    //  создаём таблицу
                    Table targetTable = new Table(_database, module.ModuleName);

                    //
                    //  добавляем базовые столбцы в таблицу
                    //
                    #region Внешниый ключ
                    Column plowMachineIdColumn = new Column(targetTable, "PlowMachineId");
                    plowMachineIdColumn.DataType = DataType.UniqueIdentifier;
                    plowMachineIdColumn.RowGuidCol = true;
                    plowMachineIdColumn.Nullable = false;

                    ForeignKey fk = new ForeignKey(targetTable, "FK_" + module.ModuleName + "_PlowMachine");
                    ForeignKeyColumn fk_column = new ForeignKeyColumn(fk, "PlowMachineId");
                    fk_column.ReferencedColumn = "PlowMachineId";
                    fk.ReferencedTable = "PlowMachines";
                    fk.Columns.Add(fk_column);

                    targetTable.ForeignKeys.Add(fk);
                    targetTable.Columns.Add(plowMachineIdColumn);
                    #endregion

                    //
                    //  добавляем столбцы в таблицу
                    //
                    foreach (FieldMetadata f in module.MetadataFields)
                    {
                        Column column = CreateColumn(targetTable, f);
                        targetTable.Columns.Add(column);
                    }

                    targetTable.Create();

                    #region Первичный ключ

                    Index idx = new Index(targetTable, "PK_" + module.ModuleName);
                    IndexedColumn idxc = new IndexedColumn(idx, plowMachineIdColumn.Name);
                    idx.IndexedColumns.Add(idxc);
                    idx.IndexKeyType = IndexKeyType.DriPrimaryKey;
                    idx.IsClustered = true;
                    idx.IsUnique = true;
                    idx.Create();

                    #endregion
                }
                catch (Microsoft.SqlServer.Management.Smo.InvalidSmoOperationException)
                {
                    throw;
                }

            }
            else
            {
                throw new InvalidOperationException("Таблица с именем '" + module.ModuleName + "' уже существует в БД.");
            }
        }
 public ForeignKeySavedEventArgs(ForeignKey key, Constraint constraint)
 {
     this.Constraint = constraint;
     this.Key        = key;
 }
Ejemplo n.º 49
0
        public void IsRequired_false_when_dependent_property_nullable()
        {
            var entityType = new Model().AddEntityType("E");
            var property = entityType.AddProperty("Id", typeof(int));
            entityType.GetOrSetPrimaryKey(property);
            var dependentProp = entityType.AddProperty("P", typeof(int?));
            dependentProp.IsNullable = true;

            var foreignKey = new ForeignKey(new[] { dependentProp }, entityType.GetPrimaryKey(), entityType, entityType);

            Assert.False(foreignKey.IsRequired);
            Assert.False(((IForeignKey)foreignKey).IsRequired);
        }
 private static string GetPropertyBaseName(ForeignKey foreignKey)
 => foreignKey.DependentToPrincipal?.Name ?? foreignKey.PrincipalEntityType.ShortName();
Ejemplo n.º 51
0
        public void IsRequired_and_IsUnique_null_when_dependent_property_nullable_by_default()
        {
            var entityType = new Model().AddEntityType("E");
            var property = entityType.AddProperty("Id", typeof(int));
            entityType.GetOrSetPrimaryKey(property);
            var dependentProp = entityType.AddProperty("P", typeof(int?));

            var foreignKey = new ForeignKey(new[] { dependentProp }, entityType.GetPrimaryKey(), entityType, entityType);

            Assert.Null(foreignKey.IsRequired);
            Assert.False(((IForeignKey)foreignKey).IsRequired);
            Assert.Null(foreignKey.IsUnique);
            Assert.False(((IForeignKey)foreignKey).IsUnique);
        }
        private InternalRelationshipBuilder ReuniquifyTemporaryProperties(ForeignKey foreignKey, bool force)
        {
            if (!force &&
                (foreignKey.GetForeignKeyPropertiesConfigurationSource() != null ||
                 !foreignKey.DeclaringEntityType.Builder.ShouldReuniquifyTemporaryProperties(
                     foreignKey.Properties,
                     foreignKey.PrincipalKey.Properties,
                     foreignKey.IsRequired,
                     GetPropertyBaseName(foreignKey))))
            {
                return(foreignKey.Builder);
            }

            var relationshipBuilder = foreignKey.Builder;

            using (var batch = foreignKey.DeclaringEntityType.Model.ConventionDispatcher.StartBatch())
            {
                var temporaryProperties = foreignKey.Properties.Where(
                    p =>
                    p.IsShadowProperty &&
                    ConfigurationSource.Convention.Overrides(p.GetConfigurationSource())).ToList();

                var keysToDetach = temporaryProperties.SelectMany(
                    p => p.GetContainingKeys()
                    .Where(k => ConfigurationSource.Convention.Overrides(k.GetConfigurationSource())))
                                   .Distinct().ToList();

                List <RelationshipSnapshot> detachedRelationships = null;
                foreach (var key in keysToDetach)
                {
                    foreach (var referencingForeignKey in key.GetReferencingForeignKeys().ToList())
                    {
                        if (detachedRelationships == null)
                        {
                            detachedRelationships = new List <RelationshipSnapshot>();
                        }

                        detachedRelationships.Add(InternalEntityTypeBuilder.DetachRelationship(referencingForeignKey));
                    }
                }

                var detachedKeys = InternalEntityTypeBuilder.DetachKeys(keysToDetach);

                var detachedIndexes = InternalEntityTypeBuilder.DetachIndexes(
                    temporaryProperties.SelectMany(p => p.GetContainingIndexes()).Distinct());

                relationshipBuilder = relationshipBuilder.HasForeignKey((IReadOnlyList <Property>)null, ConfigurationSource.Convention);

                if (detachedIndexes != null)
                {
                    foreach (var indexBuilderTuple in detachedIndexes)
                    {
                        indexBuilderTuple.Attach(indexBuilderTuple.Metadata.DeclaringEntityType.Builder);
                    }
                }

                if (detachedKeys != null)
                {
                    foreach (var detachedKeyTuple in detachedKeys)
                    {
                        detachedKeyTuple.Item1.Attach(foreignKey.DeclaringEntityType.RootType().Builder, detachedKeyTuple.Item2);
                    }
                }

                if (detachedRelationships != null)
                {
                    foreach (var detachedRelationship in detachedRelationships)
                    {
                        detachedRelationship.Attach();
                    }
                }

                return(batch.Run(relationshipBuilder));
            }
        }
Ejemplo n.º 53
0
        public void IsRequired_false_when_any_part_of_composite_FK_is_nullable()
        {
            var entityType = new Model().AddEntityType("E");
            var property = entityType.AddProperty("Id1", typeof(int));
            var property1 = entityType.AddProperty("Id2", typeof(string));
            entityType.GetOrSetPrimaryKey(new[]
                {
                    property,
                    property1
                });

            var dependentProp1 = entityType.AddProperty("P1", typeof(int));
            var dependentProp2 = entityType.AddProperty("P2", typeof(string));
            dependentProp2.IsNullable = true;

            var foreignKey = new ForeignKey(new[] { dependentProp1, dependentProp2 }, entityType.GetPrimaryKey(), entityType, entityType);

            Assert.False(foreignKey.IsRequired);
            Assert.False(((IForeignKey)foreignKey).IsRequired);

            dependentProp2.IsNullable = false;

            Assert.True(foreignKey.IsRequired);
            Assert.True(((IForeignKey)foreignKey).IsRequired);
        }
        private bool TryFindMatchingProperties(
            ForeignKey foreignKey, string baseName, bool onDependent, bool matchPK, out IReadOnlyList <Property> match)
        {
            match = null;
            var dependentEntityType = onDependent
                ? foreignKey.DeclaringEntityType
                : foreignKey.PrincipalEntityType;
            var principalEntityType = onDependent
                ? foreignKey.PrincipalEntityType
                : foreignKey.DeclaringEntityType;
            var propertiesToReference = onDependent
                ? foreignKey.PrincipalKey.Properties
                : foreignKey.DeclaringEntityType.FindPrimaryKey()?.Properties;

            if (propertiesToReference == null)
            {
                return(false);
            }

            var foreignKeyProperties = new Property[propertiesToReference.Count];
            var matchFound           = true;

            for (var i = 0; i < propertiesToReference.Count; i++)
            {
                var referencedProperty = propertiesToReference[i];
                var property           = TryGetProperty(
                    dependentEntityType,
                    baseName, referencedProperty.Name);

                if (property == null)
                {
                    matchFound = false;
                    continue;
                }

                foreignKeyProperties[i] = property;
            }

            if (!matchFound &&
                propertiesToReference.Count == 1 &&
                baseName.Length > 0)
            {
                var property = TryGetProperty(
                    dependentEntityType,
                    baseName, "Id");

                if (property != null)
                {
                    foreignKeyProperties[0] = property;
                    matchFound = true;
                }
            }

            if (!matchFound)
            {
                return(false);
            }

            if (!ForeignKey.AreCompatible(
                    propertiesToReference,
                    foreignKeyProperties,
                    principalEntityType,
                    dependentEntityType,
                    false))
            {
                if (propertiesToReference.All(
                        p => !p.IsShadowProperty ||
                        p.GetConfigurationSource().Overrides(ConfigurationSource.DataAnnotation)))
                {
                    _logger.IncompatibleMatchingForeignKeyProperties(foreignKeyProperties, propertiesToReference);
                }

                // Stop searching if match found, but is incompatible
                return(true);
            }

            foreach (var key in dependentEntityType.GetKeys())
            {
                var isKeyContainedInForeignKey = true;
                // ReSharper disable once LoopCanBeConvertedToQuery
                // ReSharper disable once ForCanBeConvertedToForeach
                for (var i = 0; i < key.Properties.Count; i++)
                {
                    if (!foreignKeyProperties.Contains(key.Properties[i]))
                    {
                        isKeyContainedInForeignKey = false;
                        break;
                    }

                    if (!foreignKey.IsUnique)
                    {
                        // Stop searching if match found, but is incompatible
                        return(true);
                    }
                }

                if (isKeyContainedInForeignKey &&
                    key.IsPrimaryKey() &&
                    !matchPK)
                {
                    // Stop searching if match found, but is incompatible
                    return(true);
                }
            }

            match = foreignKeyProperties;
            return(true);
        }
Ejemplo n.º 55
0
        public void Can_change_cascade_delete_flag()
        {
            var entityType = new Model().AddEntityType("E");
            var keyProp = entityType.AddProperty("Id", typeof(int));
            var dependentProp = entityType.AddProperty("P", typeof(int));
            var principalProp = entityType.AddProperty("U", typeof(int));
            entityType.GetOrSetPrimaryKey(keyProp);
            var principalKey = entityType.AddKey(principalProp);

            var foreignKey
                = new ForeignKey(new[] { dependentProp }, principalKey, entityType, entityType);

            Assert.Null(foreignKey.DeleteBehavior);
            Assert.Equal(DeleteBehavior.None, ((IForeignKey)foreignKey).DeleteBehavior);

            foreignKey.DeleteBehavior = DeleteBehavior.Cascade;

            Assert.Equal(DeleteBehavior.Cascade, foreignKey.DeleteBehavior);
            Assert.Equal(DeleteBehavior.Cascade, ((IForeignKey)foreignKey).DeleteBehavior);

            foreignKey.DeleteBehavior = DeleteBehavior.None;

            Assert.Equal(DeleteBehavior.None, foreignKey.DeleteBehavior);
            Assert.Equal(DeleteBehavior.None, ((IForeignKey)foreignKey).DeleteBehavior);

            foreignKey.DeleteBehavior = null;

            Assert.Null(foreignKey.DeleteBehavior);
            Assert.Equal(DeleteBehavior.None, ((IForeignKey)foreignKey).DeleteBehavior);
        }
Ejemplo n.º 56
0
        /// <summary>
        /// Sets a database record values with values retrieved from data file.
        /// </summary>
        /// <param name="rowValues"></param>
        /// <param name="record"></param>
        private bool UpdateColumnValuesInRecord(string[] rowValues, IRecord record, bool isResolvedForeignKeysChecked)
        {
            int  j = 0;
            bool isRecordUpdated = false;

            ColumnCount = 1;
            foreach (string data in rowValues)
            {
                ColumnCount++;
                if (j > this.ImportList.Count - 1)
                {
                    return(isRecordUpdated);
                }
                try
                {
                    if (this.ColumnNameList[j].ToString() != "" && ((CheckBox)this.ImportList[j]).Checked)
                    {
                        ForeignKey fkColumn      = null;
                        BaseColumn currentColumn = this.DBTable.TableDefinition.ColumnList.GetByAnyName((string)this.ColumnNameList[j]);
                        if (isResolvedForeignKeysChecked)
                        {
                            fkColumn = this.DBTable.TableDefinition.GetForeignKeyByColumnName(currentColumn.InternalName);
                        }
                        String colValue = "";

                        // Check if the foreign key has DFKA. If so, then check the calue from csv file agains the DFKA column in the parent/foreign key table.
                        // If a match is found retrieve its ID and set that as value to be insterted in the current table where you are adding records.
                        if (fkColumn != null)
                        {
                            TableDefinition originalTableDef  = fkColumn.PrimaryKeyTableDefinition;
                            BaseTable       originalBaseTable = originalTableDef.CreateBaseTable();
                            WhereClause     wc       = null;
                            ArrayList       records  = new ArrayList();
                            BaseColumn      pkColumn = (BaseColumn)originalTableDef.PrimaryKey.Columns[0];//Index is zero because we handle only those tables which has single PK column not composite keys.
                            if (fkColumn.PrimaryKeyDisplayColumns != null && fkColumn.PrimaryKeyDisplayColumns != "" && (!fkColumn.PrimaryKeyDisplayColumns.Trim().StartsWith("=")))
                            {
                                wc = new WhereClause(originalTableDef.ColumnList.GetByAnyName(fkColumn.PrimaryKeyDisplayColumns), BaseFilter.ComparisonOperator.EqualsTo, data);
                            }
                            else if (fkColumn.PrimaryKeyDisplayColumns != null && fkColumn.PrimaryKeyDisplayColumns != "" && (fkColumn.PrimaryKeyDisplayColumns.Trim().StartsWith("=")))
                            {
                                string primaryKeyDisplay = GetDFKA(fkColumn);
                                if (primaryKeyDisplay != null)
                                {
                                    wc = new WhereClause(originalTableDef.ColumnList.GetByAnyName(primaryKeyDisplay), BaseFilter.ComparisonOperator.EqualsTo, data);
                                }
                                else
                                {
                                    wc = new WhereClause(pkColumn, BaseFilter.ComparisonOperator.EqualsTo, data);
                                }
                            }
                            else
                            {
                                // if the foreign key does not have DFKA then just check in the foreign key table if the id exists. If not create a record with the specified ID
                                // before adding to current table
                                wc = new WhereClause(pkColumn, BaseFilter.ComparisonOperator.EqualsTo, data);
                            }
                            BaseClasses.Data.BaseFilter join = null;
                            records = originalBaseTable.GetRecordList(join, wc.GetFilter(), null, null, 0, 100);
                            if (records.Count > 0)
                            {
                                // take the first record and retrieve its ID.
                                BaseRecord rec = (BaseRecord)records[0];

                                colValue = (rec.GetValue(pkColumn)).ToString();
                            }
                            else
                            {
                                //  IF there is not match found then you have to create a record in the foreign key table with DFKA value and then retreive its ID
                                if (data != null & data != "")
                                {
                                    IRecord tempRec;
                                    if (fkColumn.PrimaryKeyDisplayColumns != null && fkColumn.PrimaryKeyDisplayColumns != "" && (!fkColumn.PrimaryKeyDisplayColumns.Trim().StartsWith("=")))
                                    {
                                        tempRec = originalBaseTable.CreateRecord();
                                        TableDefinition tableDef = originalBaseTable.TableDefinition;
                                        foreach (BaseColumn newCol in tableDef.Columns)
                                        {
                                            if (fkColumn.PrimaryKeyDisplayColumns == newCol.InternalName)
                                            {
                                                tempRec.SetValue(data, newCol.UniqueName);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        tempRec = originalBaseTable.CreateRecord(data);
                                    }
                                    tempRec.Save();
                                    colValue = (tempRec.GetValue(pkColumn)).ToString();
                                }
                                // colValue = data;
                            }
                        }
                        else
                        {
                            colValue = data;
                        }
                        // set the table row's column for value
                        record.SetValue(colValue, currentColumn.UniqueName);
                        isRecordUpdated = true;
                    }
                    j++;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.InnerException.Message);
                }
            }
            return(isRecordUpdated);
        }
Ejemplo n.º 57
0
 /// <summary>
 /// Create a new ForeignKey object.
 /// </summary>
 /// <param name="id">Initial value of Id.</param>
 /// <param name="ordinal">Initial value of Ordinal.</param>
 public static ForeignKey CreateForeignKey(string id, int ordinal)
 {
   ForeignKey foreignKey = new ForeignKey();
   foreignKey.Id = id;
   foreignKey.Ordinal = ordinal;
   return foreignKey;
 }
Ejemplo n.º 58
0
 public TableForeignKeyPair(Table table, ForeignKey foreignKey)
 {
     Table      = table;
     ForeignKey = foreignKey;
 }
Ejemplo n.º 59
0
 /// <summary>
 /// There are no comments for ViewForeignKeys in the schema.
 /// </summary>
 public void AddToViewForeignKeys(ForeignKey foreignKey)
 {
   base.AddObject("ViewForeignKeys", foreignKey);
 }
Ejemplo n.º 60
0
        private bool TryFindMatchingProperties(
            IConventionForeignKey foreignKey,
            string baseName,
            bool onDependent,
            bool matchPk,
            out IReadOnlyList <IConventionProperty>?match)
        {
            match = null;
            var dependentEntityType = onDependent
                ? foreignKey.DeclaringEntityType
                : foreignKey.PrincipalEntityType;
            var principalEntityType = onDependent
                ? foreignKey.PrincipalEntityType
                : foreignKey.DeclaringEntityType;
            var propertiesToReference = onDependent
                ? foreignKey.PrincipalKey.Properties
                : foreignKey.DeclaringEntityType.FindPrimaryKey()?.Properties;

            if (propertiesToReference == null)
            {
                return(false);
            }

            var foreignKeyProperties = new IConventionProperty[propertiesToReference.Count];
            var matchFound           = true;

            for (var i = 0; i < propertiesToReference.Count; i++)
            {
                var referencedProperty = propertiesToReference[i];
                var property           = TryGetProperty(
                    dependentEntityType,
                    baseName, referencedProperty.Name);

                if (property == null)
                {
                    matchFound = false;
                    continue;
                }

                foreignKeyProperties[i] = property;
            }

            if (!matchFound &&
                propertiesToReference.Count == 1 &&
                baseName.Length > 0)
            {
                var property = TryGetProperty(
                    dependentEntityType,
                    baseName, "Id");

                if (property != null)
                {
                    foreignKeyProperties[0] = property;
                    matchFound = true;
                }
            }

            if (!matchFound)
            {
                return(false);
            }

            if (!ForeignKey.AreCompatible(
                    propertiesToReference,
                    foreignKeyProperties,
                    principalEntityType,
                    dependentEntityType,
                    shouldThrow: false))
            {
                if (propertiesToReference.All(
                        p => !p.IsImplicitlyCreated() ||
                        p.GetConfigurationSource().Overrides(ConfigurationSource.DataAnnotation)))
                {
                    var dependentNavigationSpec = onDependent
                        ? foreignKey.DependentToPrincipal?.Name
                        : foreignKey.PrincipalToDependent?.Name;
                    dependentNavigationSpec = dependentEntityType.DisplayName()
                                              + (string.IsNullOrEmpty(dependentNavigationSpec)
                            ? string.Empty
                            : "." + dependentNavigationSpec);

                    var principalNavigationSpec = onDependent
                        ? foreignKey.PrincipalToDependent?.Name
                        : foreignKey.DependentToPrincipal?.Name;
                    principalNavigationSpec = principalEntityType.DisplayName()
                                              + (string.IsNullOrEmpty(principalNavigationSpec)
                            ? string.Empty
                            : "." + principalNavigationSpec);

                    Dependencies.Logger.IncompatibleMatchingForeignKeyProperties(
                        dependentNavigationSpec, principalNavigationSpec,
                        foreignKeyProperties, propertiesToReference);
                }

                // Stop searching if match found, but is incompatible
                return(true);
            }

            foreach (var key in dependentEntityType.GetKeys())
            {
                var isKeyContainedInForeignKey = true;
                // ReSharper disable once LoopCanBeConvertedToQuery
                // ReSharper disable once ForCanBeConvertedToForeach
                for (var i = 0; i < key.Properties.Count; i++)
                {
                    if (!foreignKeyProperties.Contains(key.Properties[i]))
                    {
                        isKeyContainedInForeignKey = false;
                        break;
                    }
                }

                if (isKeyContainedInForeignKey &&
                    (!foreignKey.IsUnique ||
                     (key.IsPrimaryKey() &&
                      !matchPk)))
                {
                    // Stop searching if match found, but is incompatible
                    return(true);
                }
            }

            match = foreignKeyProperties;
            return(true);
        }