Я создаю демонстрацию, ниже которой model1 - Employee
, а model2 - Department
, Employee
имеет ссылку на 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);
}
результат:
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);
})