Raida Adn
Raida Adn

Reputation: 405

Foreign key attribute not valid when trying to use in one to many relationship in EF 6

I have two POCO classes as
Employee

public class Employee
{
    public Employee()
    {
     Departments = new HashSet<Department>();
    }

[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int EmployeeId { get; set; }

public String EmployeeName { get; set; }

public int DeptId { get; set; }

[ForeignKey("DeptId")]
public  ICollection<Department> Departments { get; set; }

}

Department class

public class Department
    {      
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int DepartmentId { get; set; }
        public String Name { get; set; }
        public ICollection<Employee> Employees { get; set; }
     }

I wanted to name the foreign key in Emp-Department one to many relationship other than the default EF naming convention. So I haved used the ForeignKey attribute in Employee. But I get Exception

Foreign Key attribute on property Departments on type Employee is not valid

Help me figure out the way to name Foreign key.

Upvotes: 2

Views: 568

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89291

If Employee has a Foreign Key Property pointing to Department, then an Employee cannot have multiple Departments. So change the navigation property to:

[ForeignKey("DeptId")]
public virtual Department Department { get; set; }

Upvotes: 2

Related Questions