asp.net MVC4中的内连接查询

时间:2014-04-29 11:08:59

标签: c# sql asp.net-mvc-4

我写了关于特定员工的搜索查询,但确实没有工作,我知道我的查询中有错误,但现在确实在哪里。 我有2个表用于公司,另一个表用于员工信息。 进展将是:

  • 1' st按部门编号和公司查询公司表中的搜索 然后获得PK_companyID
  • 2' ed JOIN公司。PK_companyID==employee.FK_companyID
  • 3' ed查询将在FK_companyID时在员工表中搜索 姓名输入在employee table中将相同。

我希望明白

 var query = (from c in db.Company
            where c.departmentNO== departmentNumber && c.companyNo==companyNumber
            join x in db.Employee c.PK_companyID==x.FK_companyID
            where (x.FirstName.Contains(firstName ?? x.FirstName)
            && x.SecondName.Contains(secondName ?? x.SecondName)
            && x.ThirdName.Contains(thirdName ?? x.ThirdName)
            && x.FourthName.Contains(fourthName ?? x.FourthName))
            select x).ToList();

提前感谢。

3 个答案:

答案 0 :(得分:0)

var query = (from c in db.Company                                        
             join x in db.Employee c.PK_companyID == x.FK_companyID
         where c.departmentNO == departmentNumber && c.companyNo == companyNumber
             && (x.FirstName.Contains(firstName ?? x.FirstName)
                          && x.SecondName.Contains(secondName ?? x.SecondName)
                          && x.ThirdName.Contains(thirdName ?? x.ThirdName)
                          && x.FourthName.Contains(fourthName ?? x.FourthName))

            select x).ToList();

答案 1 :(得分:0)

您可以使用下面的代码简化查询和过滤,如果您没有使用所有过滤器,也应该使SQL更清晰。

var employees = (from c in db.Company
            join e in db.Employee on c.PK_companyID equals e.FK_companyID
            where c.departmentNO == departmentNumber && c.companyNo == companyNumber
            select e);

if (!String.IsNullOrEmpty(firstName))
    employees = employees.Where(pr => pr.FirstName.Contains(firstName));

if (!String.IsNullOrEmpty(secondName))
    employees = employees.Where(pr => pr.SecondName.Contains(secondName));

if (!String.IsNullOrEmpty(thirdName))
    employees = employees.Where(pr => pr.ThirdName.Contains(thirdName));

if (!String.IsNullOrEmpty(thirdName))
    employees = employees.Where(pr => pr.FourthName.Contains(fourthName));

return employees.ToList();

答案 2 :(得分:0)

你应该使用关键字" equals"而不是" =="在加入如下:

var query = (from c in db.Company                                        
             join x in db.Employee c.PK_companyID equals x.FK_companyID
         where c.departmentNO == departmentNumber && c.companyNo == companyNumber
         .......

希望这会奏效。