开发者

How do I change this query to linq to sql?

Query:

select emp.e开发者_如何学Pythonmpname 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?


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);


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
}


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
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜