我有以下型号
public class DeptContext : DbContext
{
public DbSet<Department> Departments { get; set; }
public DbSet<Employee> Employees { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Employee>().HasKey(t => t.EmpId);
modelBuilder.Entity<Department>().HasKey(t => t.DeptId);
}
}
public class Department
{
public int DeptId { get; set; }
public int DivNo { get; set; }
public string DeptName { get; set; }
public List<Employee> Employees { get; set; }
}
public class Employee
{
public int EmpId { get; set; }
public int DivisionNo { get; set; }
public int DepartmentId { get; set; }
public Department Department { get; set; }
}
现在我想创建一个复合主键,DeptId
并DivNo
作为部门中的键。
我在 OnModelCreating() 中添加了以下代码
modelBuilder.Entity<Department>().HasKey(t => new {t.DeptId, t.DivNo});
modelBuilder.Entity<Employee>().HasRequired(t => t.Department)
.WithMany(g=>g.Employees)
.HasForeignKey(t => new { t.DepartmentId, t.DivisionNo });
我使用了迁移,以下是我得到的代码(只有 UP())
AlterColumn("dbo.Departments", "DeptId", c => c.Int(nullable: false));
DropPrimaryKey("dbo.Departments", new[] { "DeptId" });
AddPrimaryKey("dbo.Departments", new[] { "DeptId", "DivNo" });
AddForeignKey("dbo.Employees", new[] { "DivisionNo", "DepartmentId" }, "dbo.Departments", new[] { "DeptId", "DivNo" }, cascadeDelete: true);
CreateIndex("dbo.Employees", new[] { "DivisionNo", "DepartmentId" });
现在的问题是,当我在模型构建器中添加复合外键时,我没有得到现有外键的DropForeignKey
语句,up()
得到错误为
约束“PK_dbo.Departments”被表“Employees”引用,外键约束“FK_dbo.Employees_dbo.Departments_DepartmentId”。
这是代码问题还是 ef 问题。如果是我的,请让我知道我错在哪里。
谢谢你