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問題。如果是我的,請讓我知道我錯在哪裏。
謝謝