0
我有以下型号EF复合外键得到错误
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问题。如果是我的,请让我知道我错在哪里。
谢谢