Can you add a foreign key from a table that you don't have a class model for?

237 Views Asked by At

The table A with primary key Id exists in the database. I have a model for class B:

class B{
   public int Id{get;set;}
   public int AId{get;set;}
}

Can I make AId to be a foreign key from table A without defining the model for table A?

1

There are 1 best solutions below

0
Peque Conrad On

The only solution I've found was to create an empty migration and edit Up and Down methods like this:

public partial class BIdFKs : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AddForeignKey(
            name: "FK_B_A",
            table: "dbo.B",
            column: "AId",
            principalTable: "dbo.A",
            principalColumn: "Id"
        );
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropForeignKey(
            name: "FK_B_A",
            table: "dbo.B"
        );
    }
}