-1

I have a list of int that represents service ids. and I want to make sure that all of those ids exist in the database. In other words , I want to scan the list of ids and the table of services to make sure that all of these ids exist in the database.

I tried this :

List<int> ids;//[1,52]
var x = _context.Services.Any(s => ids.Contains(s.Id));//service ids = [1,2,3]

but it returned True , which is not the desired output.

I've also tried it this way :

_context.Services.Any(s => ids.Any(id => id == s.Id)!=null);

and this way

_context.Services.Any(s => ids.Any(id => id == s.Id)!=null);

with no luck as well. what is the right way to do it? I'm using EFCore 3.1.8

SMor
  • 2,118
  • 4
  • 9
  • 12
Ataa Aub
  • 55
  • 8

1 Answers1

0

Normally you would use Queryable.Except for this.

If you have two sequence of items, and you do A except B, then if you have nothing left, then apparently every item from A is also an item in B.

IEnumerable<int> requiredIds = ...
IQueryable<int> serviceIds = dbContext.Services.Select(service => service.Id);

bool someRequiredIdsMissing = requiredIds.Except(serviceIds).Any();

Alas, your A is local and your B is in the database. So I guess this won't work.

What you can do, is to keep only Service Ids that are in the list of required Ids, and count them. If there are less, then apparently some requiredIds are not in serviceIds.

var requiredServiceIds = serviceIds.Where(serviceId => requiredIds.Contains(serviceId);

bool allRequiredAvailale = requiredServiceIds.Count() != requiredIds.Count();

Example:

IEnumerable<int> requiredIds = new [] {1, 2, 7, 20};
Total: 4 elements

Your service Ids are: 1 2 4 5 8 20 25

requiredServiceIds : 1 2 20: total 3 elements
So allRequiredAvailale is false;

Example 2:

Your service Ids are: 1 2 4 5 7 8 20 25
requiredServiceIds : 1 2 7 20: total 4 elements
So allRequiredAvailale is true;
Harald Coppoolse
  • 24,051
  • 6
  • 48
  • 92