Skip to content

Commit

Permalink
add BatchNumber for multi foreign to same table
Browse files Browse the repository at this point in the history
  • Loading branch information
Cinorid committed Jun 11, 2022
1 parent 189a741 commit 32945fe
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
2 changes: 1 addition & 1 deletion DB_to_Class/DB to Class.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<StartupObject>DB_to_Class.App</StartupObject>
<ApplicationIcon>database_restore.ico</ApplicationIcon>
<TargetFramework>net6.0-windows</TargetFramework>
<AssemblyVersion>0.1.1</AssemblyVersion>
<AssemblyVersion>0.2.0</AssemblyVersion>
</PropertyGroup>

<ItemGroup>
Expand Down
30 changes: 26 additions & 4 deletions PocoClassGenerator/PocoClassGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ INNER JOIN
}

// get foreign key columns
var foreignKeyColumns = new List<Tuple<string, string, string>>();
var foreignKeyColumns = new List<Tuple<string, string, string, string>>();
if (generatorBehavior.HasFlag(GeneratorBehavior.DapperContribExtended))
{
string sqlForeignKeys = $@"SELECT
Expand All @@ -169,7 +169,7 @@ where OBJECT_NAME(fkcol.[object_id]) = '{tableName}'
using (var reader = command.ExecuteReader())
{
while (reader.Read())
foreignKeyColumns.Add(new Tuple<string, string, string>(reader.GetString(2), reader.GetString(3), reader.GetString(4)));
foreignKeyColumns.Add(new Tuple<string, string, string, string>(reader.GetString(2), reader.GetString(3), reader.GetString(4), reader.GetString(0)));
}
}

Expand Down Expand Up @@ -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));
Expand Down

0 comments on commit 32945fe

Please sign in to comment.