如何将此查询更改为linq to sql?

时间:2010-06-17 07:33:31

标签: c# sql linq-to-sql

查询:

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'

如何将此更改为linq to sql?

3 个答案:

答案 0 :(得分:3)

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

(假设员工和部门之间的父关联在DBML中定义)

如果你期望恰到好处的一个:

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

答案 1 :(得分:1)

约:

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
}

答案 2 :(得分:1)

这就是LINQ如此出色的原因:没有理由甚至加入Departments表来使其工作:

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