Linq 实体框架 - 获取 Id 不在多对多表中的所有客户
本文关键字:客户 框架 实体 获取 Id Linq | 更新日期: 2023-09-27 18:33:38
我有 2 个表:
客户
汽车
和多对多表 MM,其中存储:
Customer_Id Car_Id
如何获取Car_Id不在多对多表中的所有客户?
我试过这样:
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));
所以基本上我为所选汽车选择所有客户,然后我检查所有客户,最后我从所有不包含 Id 的客户中选择所选客户的多到多客户表。
获取所有尚未使用汽车的客户(所有二手车在多对多表中都有所选汽车的ID)。
如果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();
您也可以将Where
更改为.Where(u=>u.Cars.All(c=>c.Id!=carId))
,可以更具可读性