如何使用流利的api添加外键?
例如
model1
id,名称,model2.id
model2
id,姓名
我已经读过select来建立一对一的关系,但是此示例显示model1仅引用了model2。
答案 0 :(得分:1)
我创建了一个演示,其下的model1为Employee
,model2为Department
,Employee
引用了Department
型号:
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);
})