2017-01-13 7 views
0

と競合Entity FrameworkのINSERT文の私は、次のクラスO.R.M. FOREIGN KEY制約例外

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); 
    } 
} 

を持っていると私は、1対多の関係を作成したいと私の構成では、私はこの

次のコードを持っています
[modelBuilder.Entity<Department>() 
      .HasMany(l => l.Employees). 
       WithRequired(r => r.Department). 
       HasForeignKey(r => r.DepartmentId); 

しかし、それはFOREIGN KEY制約と競合INSERT文

例外がスローされます\ FK_dbo.Employees_dbo.Depa rtments_DepartmentId。競合がデータベース\エンティティ\、テーブル\ dbo.Departments \、列IDで発生しました

誰でもお手伝いできますか?ありがとう

答えて

3

Employeeを保存しようとしているようですが、
Departmentがありません。したがって、関係は失敗しています。

関連する問題