Md Abdul Mannan
Md Abdul Mannan

Reputation: 40

How do i get foreign key table data using Entity Framework and Web Api in Asp.Net MVC

My Code is :

public class EmployeeController : ApiController
    {
        ASITDbEntities db = new ASITDbEntities ( );
        // GET api/employee
        public IEnumerable<Employee> Get ( )
        {
            db.Configuration.ProxyCreationEnabled = false;
            var result=db.Employees.ToList ()
            return result.ToList ( );
        }
}

I want to return employee district name from District table. It returns only district Id.

I tried db.Employee.Include(e=>e.district).Tolist(); But that did not work. Please help me.

Upvotes: 0

Views: 1758

Answers (1)

Madhu
Madhu

Reputation: 439

Firstly are you using DB first or Code-first. If code first, Does your entities looks like this?

Public class Employee{
  public int EmpId {get;set;}
  public int EmpName {get;set;}

  public int DistrictId {get;set;}
  public District District {get;set;}
}

public class District{
  public int DistrictId {get;set;}

  public List<Employee> Employees {get;set;}
}

It creates 1-1 relationship between Employee and District entities. So, now if you include db.Employee.Include(e=>e.district).Tolist(), should return you the complete District object.

Upvotes: 1

Related Questions