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

1

7

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?

Garfield answered 28/8, 2013 at 0:32 Comment(1)
Anybody have an idea?Garfield
G
13

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.

Garfield answered 30/8, 2013 at 15:54 Comment(2)
Feel free to add this to the FluentMigrator wiki. It's open to everyone.Megen
Just what I need, 7 years later, thanks JaredPentastich

© 2022 - 2024 — McMap. All rights reserved.