当只有 model1 引用其他模型时,如何使用 fluent API 添加外键?
How to add foreign key using fluent API when only model1 has reference to other model?
如何使用 fluent api 添加外键?
例如
模型 1
身份证号,姓名,model2.id
模型2
身份证、姓名
我读过有关 HasOne Method 建立一对一关系的内容,但此示例显示模型 1 仅引用模型 2。
我在下面创建了一个demo,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);
})
如何使用 fluent api 添加外键?
例如
模型 1
身份证号,姓名,model2.id
模型2
身份证、姓名
我读过有关 HasOne Method 建立一对一关系的内容,但此示例显示模型 1 仅引用模型 2。
我在下面创建了一个demo,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);
})