I have app with 3 entity models
public class Project
{
public Guid ProjectId { get; set; }
public string ProjectName { get; set; }
public string ProjectInfo { get; set; }
public Guid DepartMentId { get; set; }
public ICollection<Employee> Employees { get; set; } = new List<Employee>();
public Department Department { get; set; }
}
public class Employee
{
public Guid EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string PayrollNumber { get; set; }
public int Seniority { get; set; }
[Column(TypeName = "decimal(10,2)")]
public decimal Salary { get; set; }
public int Rank { get; set; }
public int Hours { get; set; }
public ICollection<Project> Project { get; set; }
}
public class Department
{
public Guid DepartmentId { get; set; }
public string DepartmentName { get; set; }
public string DepartmentInfo { get; set; }
public int Rank { get; set; }
public List<Project> Projects { get; set; } = new List<Project>();
}
I am create a new employee after created department and project like this
public void AddEmployee(string fname, string lname, string payNum, int seniority, decimal salary, int hours, string projname)
{
var proj = _projectController.GetProjects().Where(x => x.ProjectName == projname).SingleOrDefault();
var projects = new List<Project>();
projects.Add(proj);
var emp = new Employee { EmployeeId = Guid.NewGuid(), FirstName = fname, LastName = lname, PayrollNumber = payNum, Seniority = seniority, Salary = salary, Hours = hours, Project = projects };
_employeeController.AddEmployee(emp);
}
AddEmployee method leads to SaveChanges(); method after all and I am getting this error SqlException: Violation of PRIMARY KEY constraint 'PK_Projects'. Cannot insert duplicate key in object 'dbo.Projects'. The duplicate key value is (10bc054b-b9a7-47da-eb14-08dac1b7a7fe). The statement has been terminated. How can I fix this?