how can I add a foreign key using fluent api?
eg.
model1
id, name, model2.id
model2
id, name
I've read about HasOne Method for building one to one relationship but this example shows the model1 only have reference to model2.
I create a demo below which model1 is Employee
and model2 is Department
, Employee
has a reference to Department
models:
public class Employee
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int DepartmentId { get; set; }
public Department Department { get; set; }
}
public class Department
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
dcContext:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Employee>()
.HasOne(e => e.Department)
.WithOne()
.HasForeignKey<Employee>(e => e.DepartmentId);
}
result:
migrationBuilder.CreateTable(
name: "Employees",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(nullable: true),
DepartmentId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Employees", x => x.Id);
table.ForeignKey(
name: "FK_Employees_Department_DepartmentId",
column: x => x.DepartmentId,
principalTable: "Department",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})