简体   繁体   English

LINQ to SQL 查询多对多关系

[英]LINQ to SQL Query for Many-to-Many relationship

I am moving an old ASP.net (C#) application from plain SQL queries to LINQ to SQL and am having some trouble with some of the more complex queries.我正在将旧的 ASP.net (C#) 应用程序从普通 SQL 查询迁移到 LINQ to SQL,并且在处理一些更复杂的查询时遇到了一些麻烦。 In this case, I am trying to get a list of employees who have a certain set of skills.在这种情况下,我试图获取具有特定技能的员工列表。 The user picks the skills to search for and the id's are supplied to the method that does the work.用户选择要搜索的技能,并将 ID 提供给执行工作的方法。 In the old SQL version, I just appended WHERE clauses to the string for each skill.在旧的 SQL 版本中,我只是将 WHERE 子句附加到每个技能的字符串中。 Here's an example query:这是一个示例查询:

SELECT DISTINCT e.firstname, e.lastname, e.username
FROM employees AS e
WHERE e.id IN (SELECT es.emp_id 
FROM emp_skl AS es 
WHERE es.skl_id = 6 OR es.skl_id = 11 
GROUP BY es.emp_id
HAVING COUNT(es.emp_id) >= 2)

The key is the HAVING COUNT clause since that ensures the employees returned have ALL the skills and not just one.关键是 HAVING COUNT 子句,因为它确保返回的员工拥有所有技能,而不仅仅是一项技能。 Anyway, can someone help me turn this into a solid LINQ query?无论如何,有人可以帮我把它变成一个可靠的 LINQ 查询吗?

替代文字

First of all, it's better if your tables don't end with an "S".首先,最好不要以“S”结尾。

Now the code, asuming you have already a function yo get a list of skills:现在代码,假设你已经有了一个函数,你会得到一个技能列表:

IQueryable<skills> listSkills = getSkills();
IQueryable<employees> listEmployees = db.employees;

foreach(var skill in listSkills)
{
    listEmployees=listEmployees
        .Where(p=>p.emp_skls.Any(q=>q.skl_id==skill.id));
}

Edit:编辑:

for instance:例如:

public IQueyable<skills> getSkills()
{
    return db.skills.Where(p=>p.id==6 || p.id==1);
}

Here's the LINQ translation of your SQL query:这是您的 SQL 查询的 LINQ 翻译:

from e in Employees
where e.Emp_Skls.Count (es => es.Skl_id == 6 || es.skl_id == 11) >= 2
select new
{
  e.FirstName, e.LastName, e.UserName
}

However, if your desired query is "give me employees who have both skills 6 and 11", your SQL query will fail if skill 6 or 11 appears twice for an employee (I take it this is possible because you have >= 2 rather than =2 in your having clause).但是,如果您想要的查询是“给我同时拥有技能 6 和 11 的员工”,那么如果员工的技能 6 或 11 出现两次,您的 SQL 查询将失败(我认为这是可能的,因为您有 >= 2 而不是=2 在你的 have 子句中)。 In which case, the following query is a better fit:在这种情况下,以下查询更适合:

from e in Employees
where e.Emp_Skls.Any (es => es.Skl_id == 6) &&
      e.Emp_Skls.Any (es => es.Skl_id == 11)
select new
{
  e.FirstName, e.LastName, e.UserName
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM