By using Single LINQ Query retrieve foriegn key table column

In this article, I will explain you, How to retrieve data from two joined table using single LINQ Query. Here we have two joined table in mentioned diagram. Both tables are joined from dept_no, so if you want to retrieve record from both table like:
Retrieve emp_id and emp_name who belongs to IT department.



employeeEntities empl = new employeeEntities();

            var query = from g in empl.emps
                        join m in empl.depts on g.dept_no equals m.dept_no
                        where m.dept_name == "IT"
                        select new
                        {
                            Emp_Name = g.emp_name,
                            Emp_ID = g.emp_id
                        };
               
            dataGridView1.DataSource = query.ToList();
In this code, empl is the context object through which we can access columns of both tables. emp is the foreign key table map with dept table using dept_no column. Emp_Name and Emp_ID is the reference name , which are displayed on table. Bind the query result with the dataGridView. 
By using Single LINQ Query retrieve foriegn key table column By using Single LINQ Query retrieve foriegn key table column Reviewed by Jacob Lefore on February 10, 2016 Rating: 5

2 comments

  1. Why not:
    var query = empl.emps
    .Where(i => i.dept.dept_name == "IT")
    .Select(i => new {Emp_Name = i.emp_name, Emp_Id = i.emp_id });

    Since you already have a navigational property.

    ReplyDelete
  2. you can use lambda expression, thanks for valuable comments

    ReplyDelete