简体   繁体   English

选择实体框架中另一个表中不存在的记录

[英]Select records that does not exist in another table in Entity Framework

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.当我将客户列入黑名单时,我将 customerid 作为外键添加到 Blacklist 表中。

What I want is to get CusId and Name that are not in the BlackList Table.我想要的是获取不在 BlackList 表中的 CusId 和 Name。

How can I code this Entity Framework C#?如何编写此实体框架 C#?

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

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

What you want is something like the following:您想要的是以下内容:

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

EF will happily turn that into a sub-query that will run quite well. EF 很乐意将其转换为运行良好的子查询。

This pattern works for static lists (creates an IN(a, b, c) expression) as well as other tables.此模式适用于静态列表(创建IN(a, b, c)表达式)以及其他表。 You can use it to check for being in the list or not in the list.您可以使用它来检查是否在列表中。

If you want to test it and see the SQL it generates, I strongly recommend LINQPad (it is free).如果您想测试它并查看它生成的 SQL,我强烈推荐 LINQPad(它是免费的)。 That's what I use to test out little ideas in LINQ all the time.这就是我一直用来在 LINQ 中测试小想法的方法。

How about something like this:这样的事情怎么样:

var subselect = (from b in BlackList select b.CusId).ToList();

var result = from c in Customer where !subselect.Contains(c.CusId) select c;

IF in table BlackList yo have a List of Customer You can perform something like如果在表BlackList有一个Customer列表,您可以执行类似的操作

 IEnumerable<Customer> model = (from c in db.Customer
                                from b in c.BlackList.DefaultIfEmpty()
                                 where b.CusID== null
                                  select new Customer
                                   {
                                        CusId= c.OrderID
                                    }).ToList();

Any() is the best performance : Any() 是最好的性能:

db.Customers.Where(c => !db.Blacklists.Any(b => b.CusId == c.Id));

If you also need columns of Blacklists , use join with condition : b.CusId == c.Id如果您还需要黑名单,使用与加盟条件:b.CusId == c.Id

我使用了这个查询,它完美地工作:

var query = _context.Customer.Where(x => x.Id == id && !x.BlackList.Any(z => x.Id == x.CustId)).ToList();

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

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