[英]Linq Entity Framework - get all customers that Ids are not in many to many table
I have 2 tables: 我有2张桌子:
Customer 顾客
Car 汽车
and many-to-many table MM, which stores: 和多对多表MM,它们存储:
Customer_Id Car_Id Customer_Id Car_Id
How do I get all Customers which Car_Id's are not in many to many table? 如何让所有Car_Id不在多个表中的客户?
I tried like this: 我试过这样的:
public async Task<IEnumerable<CustomerModel>> GetNewCustomersForCar(int carId)
{
var sentCustomers = await _unit.Repository<Car>().Queryable()
.SelectMany(a => a.AspNetUsers, (b, a) => new { b, a })
.Where(b => b.Id == carId)
.Select(ba => new CustomerModel()
{
Id = ba.a.Id,
Email = ba.a.Email
})
.ToListAsync();
var allCustomers = await _unit.Repository<AspNetUser>().Queryable()
.Select(c => new CustomerModel()
{
Id = c.Id,
Email = c.Email
}).ToListAsync();
return allCustomers.Where(ac => !sentCustomers.Contains(ac));
So basically I select all customers for selected car, then I check all customers, and in the end I select from all customers that do not contain Id's from many to many customer table for selected customer. 所以基本上我选择了所选客户的所有客户,然后我检查所有客户,最后我从所有客户中选择不包含Id的客户表中的所有客户表。
Get all customers which didn't use car yet(all that used car are having id's for selected car in many to many table). 获取所有尚未使用汽车的客户(所有二手车都在许多表中选择了汽车的id)。
if you have a Cars
navigation property in your AspNetUser
entity, you could do this: 如果您的
AspNetUser
实体中有Cars
导航属性,则可以执行以下操作:
var query= await _unit.Repository<AspNetUser>()
.Queryable()
.Where(u=>!u.Cars.Any(c=>c.Id==carId))
.Select(c => new CustomerModel()
{
Id = c.Id,
Email = c.Email
})
.ToListAsync();
Also you can change your Where
to .Where(u=>u.Cars.All(c=>c.Id!=carId))
,could be more readable 你也可以改变你的位置。
Where
.Where(u=>u.Cars.All(c=>c.Id!=carId))
,可能更具可读性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.