为了账号安全,请及时绑定邮箱和手机立即绑定

Entity Framework Core 排除结果

Entity Framework Core 排除结果

C#
GCT1015 2022-01-09 16:40:06
使用 Entity Framework Core 和 ASP.NET Core 2.1,如何返回一个表的结果,但前提是在第二个表中找不到该行 ID?例如,应仅返回 Entity1 表中的前两行,因为第三行具有存储在 Entity2 表中的引用。Entity1 表+-----------+-----------+| Entity1Id | Name      |+-----------+-----------+| 1         | Row One   || 2         | Row Two   || 3         | Row Three |+-----------+-----------+Entity2 表+-----------+-----------+-----------+| Entity2Id | Name      | Entity1Id |+-----------+-----------+-----------+| 1         | Row One   | 3         |+-----------+-----------+-----------+
查看完整描述

2 回答

?
动漫人物

TA贡献1815条经验 获得超10个赞

你可以做...

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

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


查看完整回答
反对 回复 2022-01-09
?
慕娘9325324

TA贡献1783条经验 获得超5个赞

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

//img1.sycdn.imooc.com//61da9f9500010a8103150036.jpg

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


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 ;


查看完整回答
反对 回复 2022-01-09
  • 2 回答
  • 0 关注
  • 197 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号