How to create one to one foreign key using FluentMigrator
Asked Answered
G

1

6

I'm using this code for creating foreign key:

Create.ForeignKey("FK_Table1_Table2")
    .FromTable("Table1").ForeignColumn("Table1_ID")
    .ToTable("Table2").PrimaryColumn("Table2_ID");

And as a result I have one to many relationship:

public class Table1
{
    public int Table1_ID { get; set; }
    public virtual Table2 Table2 { get; set; }
}


public class Table2
{
    public Table2()
    {
        this.Tables1 = new HashSet<Table1>();
    }
    public int Table2_ID { get; set; }
    public virtual ICollection<Table1> Tables1 { get; set; }
}

but I want to see:

public class Table2
{
    public int Table2_ID { get; set; }
    public virtual Table1 Table1 { get; set; }
}

Is there way to do that with using FluentMigrator?

Ghost answered 22/4, 2019 at 8:19 Comment(0)
I
4

Relational databases have no special notion for many/one to one FK relationship. The only way FK becomes "one" is if it also has unique constraint.

So I believe you should add something like this after foreign key creation code:

Create.UniqueConstraint()
    .OnTable("Table1").Column("Table1_ID");
Integrated answered 22/4, 2019 at 8:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.