Tuesday, September 24, 2019

EF Core joining tables using Include and selecting specific columns

In the previous posts we saw on how to join tables using Include and how to select specific columns form a table. In this post we will try to combine both of them, we will join tables using Include and select specific columns from the joined tables.

We will join the Employee table with Department and Country tables, select specific columns from each of the table and populate the below Model class.
    public class EmployeeDetail
    {
        public int EmployeeId { get; set; }
        public string Department { get; set; }
        public string Name { get; set; }
        public int? Age { get; set; }
        public string Country { get; set; }
    }

The EF Core code to join the tables and select the required columns is as follows.

        [HttpGet(
"GetEmployeeDetails")]
        public ActionResult<List<EmployeeDetail>> Get()
        {
            var _context = new UserRegistrationContext();
            var employeeList = _context.Employee
                                    .Include("Department")
                                    .Include("Country")
                                    .AsEnumerable()
                                    .Select(e => new EmployeeDetail
                                    {
                                        EmployeeId = e.EmployeeId,
                                        Department = e.Department.Name,
                                        Name = e.Name,
                                        Age = e.Age,
                                        Country = e.Country.Name
                                    }).ToList();
            return employeeList;
        }
Build the project, in postman let us invoke the following endpoint. Notice that we are getting data from multiple tables populated using the custom Model class.




Search Flipkart Products:
Flipkart.com

No comments: