簡體   English   中英

使用linq檢查是否不存在子句

[英]Using linq to check if not exists clause

這是我一直試圖解決的情況

讓我們拿一個員工表

Create Table Employee
(
        Employeeid int primary key,
        EMPname varchar(50),
        ManagerEmplId int reference key Employee (EmployeeID)
         TreeLevel int,
              ....
)

在這里,我需要找到所有葉子級員工。

一級員工-具有經理但沒有任何人向其報告的所有員工。 我從db有TreeLevel列的數據庫中獲得了一些幫助,我可以在其中指定在3級選擇任何人,但是我需要一個UNIONclause,它將使我在2級沒有任何員工報告的所有員工。 我只有3個級別的樹,如果這有助於創建linq查詢。

   return ((from b in _db.Employees
                && b.TreeLevel==3 && b.DeletedDate== null
                    select b)
                    .Union
                    (from b in _db.Employees

                     select b)

                    )
                    .ToDictionary(k => k.EmployeeID, v => v.EMPname);

更新:真正的查詢:

(from fi in firm 
 join bra in _db.Branches on fi.BranchID equals bra.ParentBranchID into g 
 from sc in g.DefaultIfEmpty() 
 where fi.DeletedDate == null && g == null 
 select fi)
 .ToList()
 .ToDictionary(k => k.BranchID, v => v.BranchName);

錯誤:

Cannot compare elements of type 'System.Collections.Generic.IEnumerable`1'. 
Only primitive types (such as Int32, String, and Guid) and entity types are supported.

無論樹的深度如何,此查詢都可以解決問題:

var leafEmps = 
    (from emp in _db.Employees
     where !_db.Employees.Any(e => e.ManagerEmplId == emp.EmployeeId)
     select emp);

您可以嘗試右外部聯接,並確保左側為空。

在這篇文章中, 如何在Linq中進行完全外部聯接? 您可以在linq中找到一個很好的例子。

from b in _db.Employees
from c in _db.Employees.Where(o=> o.ManagerEmplId == b.Id).DefaultIfEmpty()
where c == null
var managersids = _db.Employees.Select(emp => emp.ManagerEmplId ).Distinct();
var leafemps = _db.Employees.where(emp => !managersids.contains(emp.Employeeid));

為此,請獲取所有經理,然后搜索不是經理的人員

var leafemps = from emp in _db.Employees
               let managersids = _db.Employees.Select(emp => emp.ManagerEmplId ).Distinct()
               where !managersids.contains(emp.Employeeid)
               select emp

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM