Entity framework set navigation property

We have database which does not have proper foreign keys set. We are now generating edmx using this database. What we want is to set navigation property so that we can get corresponding details from other table. Here is example what exactly we are looking for.

Lets say There is a table Employee and Department. Now in database there is no relation between these tables but Employee has DepartmentId which is taken from Department table.

When we fetch Employee we get only DepartmentID but we also want to get Department as property along with it so that we can get information like "DepartMentName", "Location" which is stored in Department table.

We tried adding Navigation property in EDMX file but it fails and keeps giving error related to relation.

Please help

Upvotes: 0

Views: 829

Answers (1)

Manoj
Manoj

Reputation: 634

You can go with something like this. Create a wrapper class for Employee and Department.

public class EmpDept
{
    public Employee Employee { get; set; }
    public Department Department { get; set; }
}

public IEnumerable<EmpDept> GetEmployeesWithDeptpartment()
{        
    var result = from e in context.Employee
                 where e.Id == somevalue
                 select new EmpDept()
                        {
                            Employee = e,
                            Department = context.Department.Where(d => d.Id == e.DepartmentId)
                        };

    return result.ToList();
}

It means you have an extra class, but it's quick and easy to code, easily extensible, reusable and type-safe.

Hope this helps

Upvotes: 4

Related Questions