Search code examples
c#ado.netentity-framework-6navigation-properties

Entity Framework Navigation property not working


I have a many to many relationship like below.

  • Company[CompanyID, Name] - nav prop SalaryTabs
  • SalaryTab[ID,Salary, Since, CompanyId, Employeeid] - nav prop (Company, Employee), and
  • Employee[EmployeeID,FirstName, LastName, DOB] -nav prop
    (SalaryTabs)

But When I try to use Linq to query the tables using the navigation property. It wont just show up in the intellisence at all.

For example, I want to access contxt.SalaryTabs.Company.xxx The navigation property Company will not load the xxx and will not show up in the intellisence and if I manually type it. I get some errors.

If I try to do something like

//Delete an employee (identified via id) from a specific company(identified via id)

public bool DeleteEmployeeFromSpecificCompany(Guid employeeID, Guid companyID)
{
    try
    {
        var emp = dbContext.Employees.FirstOrDefault(x => x.EmployeeID == employeeID);
        dbContext.Companies.FirstOrDefault(x => x.CompanyID == companyID).SalaryTabs.Employee.Remove(emp);

        dbContext.SaveChanges();
    }
    catch (Exception)
    {
        return false;
    }
    return true;
}

The navigation property doesn't work. I can't access context.Companies.SalaryTab.xxxx for example. I have been having this problem since yester which I didn't have before. I could navigate from one entity to another using the navigation properties but now it won't load and offer the options anymore.

I appreciate any input.


Solution

  • SalaryTabs - is collection. So, you need select one:

    dbContext.Companies.FirstOrDefault(x => x.CompanyID == companyID).SalaryTabs.FirstOrDefault(...condition...)