'How to write this query without for loop

I have three tables with m-to-m relationship. Customer - CustomerCars - Car

I receive a dictionary with a CustomerId as a key and an array of his CarId as value

public IDictionary<int,IEnumerable<CarsIdsDto>> Data { get; set; }

I want to delete some cars from many customers(CarsIdsDto are the Ids of cars that must remain), so my code for this looks like this

foreach (var entry in message.Data)
{
    var cars = await _context.CustomerCars
        .Where(x => x.CustomerId == entry.Key)
        .ToListAsync(cancellationToken);

    var newIds = entry.Value.Select(x => x.CarId).ToList();

    //Delete
    var carsToDelete = cars.Where(x => !newIds.Contains(x.CarId));


    await _context.CustomerCars.RemoveRangeAsync(carsToDelete,
        cancellationToken
    );
}

The code works fine, but it creates a query for every customer Can it be refactored to delete all customer cars in one query?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source