2013-04-10 87 views
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; } 
} 

現在我想創建一個DeptIdDivNo複合主鍵在按鍵部門。

我已經添加了以下代碼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問題。如果是我的,請讓我知道我錯在哪裏。

謝謝

回答

0

對我來說,它看起來像一個遷移中的錯誤。沒有辦法如何你的代碼可以搞砸了。

但我強烈的建議是不使用複合主鍵特別是而不是其中一個字段在業務領域(其中DivisionNo有?)有意義。複合主鍵增加了比通過引入它們而獲得的更多複雜性。它們只應出現在聯結表中。

看起來你應該引入一個類/表Division。我不明白DivNo可以添加到Department的標識中。如果你有兩個部門具有相同DeptId和不同DivNo S,那會是完全不同的部門?