将Linq中的语句加入Sql

时间:2011-08-09 22:12:49

标签: linq linq-to-sql

我需要在linq中编写查询后编写Join statment 例如:

var Query = (from Tab in Db.Employees
              select Tab)

因为我有一些情况要执行连接操作所以 我需要在此查询Query.Join(Join with another Table like Department);上执行此操作我需要语法

if (DeptID != -1){ Query.Join(Join with table Department where FkDeptID = DeptID); }

2 个答案:

答案 0 :(得分:0)

考虑在LINQ'查询语法'中使用join:

from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}

这样的东西?

var results = (from q in Query 
               join m in myList  on q.SomeID = m.SomeID
               select unknown);

答案 1 :(得分:0)

尝试使用此查询:

var Query =
    from e in Db.Employees
    join d in Db.Departments on e.FkDeptID equals d.DeptID into departments
    select new
    {
        Employee = e,
        Department = departments.SingleOrDefault(),
    };

这可以假设e.FkDeptID == -1 Departments表中没有记录,Department null将被分配SingleOrDefault

您不应该为员工设置多个部门,因此我使用FirstOrDefault而不是{{1}}。