Can I use an extension method to add a column AND a foreign key constraint with Fluent Migrator?

StackOverflow https://stackoverflow.com/questions/18477574

  •  26-06-2022
  •  | 
  •  

I have an extension method that is used by several tables:

public static ICreateTableColumnOptionOrWithColumnSyntax WithUser(this ICreateTableWithColumnSyntax tableWithColumnSyntax)
{
    return tableWithColumnSyntax
        .WithColumn("UserId")
            .AsInt32()
            .Nullable();
}

Here is an example table using it:

Create.Table("UserSettings")
    .WithUser()
    .WithColumn("SomeValue")
        .AsString(1)
        .Nullable();

I then have to add a foreign key manually every time like so:

Create.ForeignKey()
    .FromTable("UserSettings")
       .ForeignColumn("UserID")
   .ToTable("Users")
       .PrimaryColumn("Id");

Is there a way to package the foreign key declaration in the extension method WithUser() so that I (and more importantly, other people on my team) don't have to specify it every time?

有帮助吗?

解决方案

This ended up being easier than expected. Here is the code to do this:

public static ICreateTableColumnOptionOrWithColumnSyntax WithUser(this ICreateTableWithColumnSyntax tableWithColumnSyntax)
{
    return tableWithColumnSyntax
        .WithColumn("UserId")
            .AsInt32()
            .Nullable()
            .ForeignKey("Users", "Id");
}

I just wish this was better documented somewhere.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top