实体框架核心排除结果

问题描述 投票:0回答:2

使用Entity Framework Core和ASP.NET Core 2.1,如何返回一个表的结果,但仅当在第二个表中找不到该行id时?

例如,只应返回Entity1表中的前两行,因为第三行具有存储在Entity2表中的引用。

实体1表

+-----------+-----------+
| Entity1Id | Name      |
+-----------+-----------+
| 1         | Row One   |
| 2         | Row Two   |
| 3         | Row Three |
+-----------+-----------+

实体2表

+-----------+-----------+-----------+
| Entity2Id | Name      | Entity1Id |
+-----------+-----------+-----------+
| 1         | Row One   | 3         |
+-----------+-----------+-----------+
c# sql-server asp.net-core entity-framework-core
2个回答
2
投票

你可以......

var result = dbContext.Entity1.Where(w => !w.Entity2.Any()).ToList();

这应该返回没有Entity2记录的所有Entity1行。


1
投票

最直接的方法是使用可以描述如下的子查询:

enter image description here

现在我们可以轻松地将公式转换为以下代码:

IQueryable<Entity1> q = _context.Entity1.FromSql(
    @"select * from Entity1 
    where not exists(
        select Entity2.Id from Entity2 where Entity2.Entity1Id = Entity1.Id
    )"
);

另一种方法是左外连接:

IQueryable<Entity1> q = from i in _context.Entity1
                        join j in _context.Entity2 on i.Id equals j.Entity1Id into jj
                        from x in jj.DefaultIfEmpty()
                        where jj.All(x=> x.Entity1Id!=i.Id)
                        select i ;
© www.soinside.com 2019 - 2024. All rights reserved.