I have a simple model:
class Employee {
int EmployeeId {get;set;}
List<Task> Tasks {get;set;}
}
class Manager {
int ManagerId {get;set;}
List<Task> Tasks {get;set;}
}
class Task {
int TaskId {get;set;}
EmployeeId {get;set;}
ManagerId {get;set;}
[ForeignKey("EmployeeId")]
Employee Employee {get;set;}
[ForeignKey("ManagerId")]
Manager Manager {get;set;}
}
class Task1 : Task { }
class Task2 : Task { }
when I try to seed the database I get an exception, this is how I'm seeding:
Employee employee = new Employee();
context.Employees.Add(employee);
context.SaveChanges();
Manager manager = new Manager();
context.Managers.Add(manager);
context.SaveChanges();
List<Task> EmpTask = new List<Task>();
//EXCEPTION OCCURS HERE WHEN I TRY TO ADD NEW TASK ITEMS
Task EmpOne = new Task1();
Task EmpTwo = new Task2();
EmpTask.Add(EmpOne);
EmpTask.Add(EmpTwo);
Employee.Tasks = EmpTask;
Context.Entry(employee).State = EntityState.Modified;
Context.SaveChanges();
List<Task> ManagerTask = new List<Task>();
Task ManagerOne = new Task1();
Task ManagerTwo = new Task2();
ManagerTask.Add(ManagerOne);
ManagerTask.Add(ManagerTwo);
Manager.Tasks = ManagerTask;
Context.Entry(manager).State = EntityState.Modified;
Context.SaveChanges();
The exception I keep getting is:
{"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.Task_dbo.Employee_EmployeeId\". The conflict occurred in database \"GIP\", table \"dbo.Employee\", column 'EmployeeId'.\r\nThe statement has been terminated."}
When I change my code to the following, however, I have no issues (seeding the same way, but no Manager portion):
class Employee {
int EmployeeId {get;set;}
List<Task> Tasks {get;set;}
}
class Task {
int TaskId {get;set;}
int EmployeeId {get;set;}
[ForeignKey("EmployeeId")]
Employee Employee {get;set;}
}
it seems like when the Task class has 2 foreign key constraints its getting confused or something...
Also, if I add the Manager class back, but REMOVE ALL ForeignKey constraints from the Task class, it has no issues because it creates it's own auto-generated foreign key columns in the database, with some employee foreign keys being Null for manager tasks, and manager foreign keys being null for employee tasks
Make sure that your FK columns are nullable, eg.
int?
instead ofint
. If they are not null, then they are 0 by default, which will reference an entity with the 0 key, and that will violate the FK constraint.If you are going to specify your own foreign keys, the properties must be virtual.
Example:
[ForeignKey("Employee")] public virtual int EmployeeId { get; set; }
[ForeignKey("EmployeeId")] public virtual Employee Employee { get; set; }