diff --git a/DB_to_Class/DB to Class.csproj b/DB_to_Class/DB to Class.csproj index b5e1521..d82e4bc 100644 --- a/DB_to_Class/DB to Class.csproj +++ b/DB_to_Class/DB to Class.csproj @@ -6,7 +6,7 @@ DB_to_Class.App database_restore.ico net6.0-windows - 0.1.1 + 0.2.0 diff --git a/PocoClassGenerator/PocoClassGenerator.cs b/PocoClassGenerator/PocoClassGenerator.cs index 1ac7fc2..14e61da 100644 --- a/PocoClassGenerator/PocoClassGenerator.cs +++ b/PocoClassGenerator/PocoClassGenerator.cs @@ -144,7 +144,7 @@ INNER JOIN } // get foreign key columns - var foreignKeyColumns = new List>(); + var foreignKeyColumns = new List>(); if (generatorBehavior.HasFlag(GeneratorBehavior.DapperContribExtended)) { string sqlForeignKeys = $@"SELECT @@ -169,7 +169,7 @@ where OBJECT_NAME(fkcol.[object_id]) = '{tableName}' using (var reader = command.ExecuteReader()) { while (reader.Read()) - foreignKeyColumns.Add(new Tuple(reader.GetString(2), reader.GetString(3), reader.GetString(4))); + foreignKeyColumns.Add(new Tuple(reader.GetString(2), reader.GetString(3), reader.GetString(4), reader.GetString(0))); } } @@ -223,8 +223,30 @@ where OBJECT_NAME(fkcol.[object_id]) = '{tableName}' builder.AppendLine(" [UniqueConstraint]"); var foreignKeys = foreignKeyColumns.Where(f => f.Item1 == collumnName).ToList(); - if(foreignKeys.Any()) - builder.AppendLine(" [ForeignKey(typeof(" + foreignKeys.First().Item2 + "), \"" + foreignKeys.First().Item3 + "\")]"); + if (foreignKeys.Any()) + { + var foreignKey = foreignKeys.First(); + + var foreignKeyGroups = foreignKeyColumns + .Where(x=> x.Item2 == foreignKey.Item2 && x.Item3 == foreignKey.Item3) + .OrderBy(x => x.Item4) + .ToList(); + if(foreignKeyGroups.Count() > 1) + { + for (var batchNumber = 0; batchNumber < foreignKeyGroups.Count; batchNumber++) + { + if (foreignKey == foreignKeyGroups[batchNumber]) + { + builder.AppendLine(" [ForeignKey(typeof(" + foreignKey.Item2 + "), \"" + foreignKey.Item3 + "\", " + (batchNumber + 1) + ")]"); + break; + } + } + } + else + { + builder.AppendLine(" [ForeignKey(typeof(" + foreignKey.Item2 + "), \"" + foreignKey.Item3 + "\")]"); + } + } } builder.AppendLine(string.Format(" public {0}{1} {2} {{ get; set; }}", name, isNullable ? "?" : string.Empty, collumnName));