2017-01-13 74 views
0

我有以下類O.R.M.實體框架INSERT語句衝突與外鍵約束的例外

public class Employee 
{ 
    public Guid Id { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string Gender { get; set; } 
    public int Salary { get; set; } 
    public string PhoneNumber { get; set; } 
    public Guid DepartmentId { get; set; } 
    public virtual Department Department { get; set; } 
    public int Deleted { get; set; } 

    public bool IsDeleted() 
    { 
     return this.Deleted == 1 ? true : false; 
    } 

    public void MarkAsDeleted() 
    { 
     this.Deleted = 1; 
    } 

    public string GetFullName() 
    { 
     return this.FirstName + " " + this.LastName; 
    } 
} 

public class Department 
{ 
    public Department() 
    { 
     this.Employees = new List<Employee>(); 
    } 

    public Guid Id { get; set; } 
    public string Name { get; set; } 
    public virtual List<Employee> Employees { get; set; } 
    public int Deleted { get; set; } 

    public bool IsDeleted() 
    { 
     return this.Deleted == 1 ? true : false; 
    } 

    public void MarkAsDeleted() 
    { 
     this.Deleted = 1; 
    } 

    public void AddEmployee(Employee employee) 
    { 
     this.Employees.Add(employee); 
    } 

    public void RemoveEmployee(Employee employee) 
    { 
     this.Employees.Remove(employee); 
    } 
} 

我想創建一個一對多的關係,在我的配置我有這個

下面的代碼
[modelBuilder.Entity<Department>() 
      .HasMany(l => l.Employees). 
       WithRequired(r => r.Department). 
       HasForeignKey(r => r.DepartmentId); 

但它拋出一個異常

INSERT語句衝突與外鍵約束\ FK_dbo.Employees_dbo.Depa rtments_DepartmentId。衝突發生在數據庫\ Entities \,表\ dbo.Departments \中,列Id

任何人都可以幫我嗎?謝謝

回答

3

看來,在某些時候,你試圖保存一個Employee沒有
Department。因此,這種關係失敗了。

相關問題