选择在实体框架的另一个表中不存在的记录 [英] Select records that does not exist in another table in Entity Framework

查看:46
本文介绍了选择在实体框架的另一个表中不存在的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表-客户表和黑名单客户表。当我将客户列入黑名单时,我会将customerid作为外键添加到黑名单表中。

I have two tables - "Customer" table and "Blacklist" customer table. When I blacklist a customer, I put the customerid as a foreign key to Blacklist table.

我想要的是获取不在黑名单表中的CusId和Name。

What I want is to get CusId and Name that are not in the BlackList Table.

如何编码此实体框架C#?

How can I code this Entity Framework C#?

Customer
---------
(CusId,Name,Telephone,Email)

Blacklist
---------
(CusId)


推荐答案

您想要的是类似

db.Customers
    .Where(c => !db.Blacklists
        .Select(b => b.CusId)
        .Contains(c.CusId)
    );

EF会很乐意将其转换为运行良好的子查询。

EF will happily turn that into a sub-query that will run quite well.

此模式适用于静态列表(创建 IN(a,b,c)表达式)以及其他表。您可以使用它来检查是否在列表中。

This pattern works for static lists (creates an IN(a, b, c) expression) as well as other tables. You can use it to check for being in the list or not in the list.

如果要测试它并查看它生成的SQL,我强烈建议使用LINQPad(这是免费的)。这就是我一直在测试LINQ中的小创意的方法。

If you want to test it and see the SQL it generates, I strongly recommend LINQPad (it is free). That's what I use to test out little ideas in LINQ all the time.

这篇关于选择在实体框架的另一个表中不存在的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆