Piyush
Piyush

Reputation: 11

How do I change this query to linq to sql?

Query:

select emp.empname as Name, dep.depname as Department 
from Employee as emp 
inner join Department as dep on emp.depid=dep.depid 
where emp.id='2'

How can I change this to linq to sql?

Upvotes: 1

Views: 91

Answers (3)

Steven
Steven

Reputation: 172646

This is why LINQ is so great: there is no reason to even join with the Departments table to get it to work:

from employee in db.Employees
where employee.id == 2
select new
{
    Name = employee.empname, 
    Department = employee.Department.depname
};

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062770

var id = 2;
var qry = from e in db.Employees
          where e.Id == id
          select new {
              Name = e.EmpName,
              Department = e.Department.DepName
          };

(assumes the parent-association between employee and department is defined in the DBML)

and if you expect exactly one such:

var record = qry.Single();
Console.WriteLine(record.Name);
Console.WriteLine(record.Department);

Upvotes: 3

Murph
Murph

Reputation: 10190

Approximately:

from e in dc.Employee
join d in dc.Department on e.depid equals d.depid
where e.id == '2'
select new
{
    Name = e.empname,
    Department = d.depname
}

Upvotes: 1

Related Questions