Better way to check if a list of IDs is valid (EF Core)

c# entity-framework-core linq

Question

I have a list of checkbox elements in a html page, all selectable and with distinct IDs, and its IDs are send by HTTP POST to my API. For security, I need to check if any of the sent IDs is invalid. It is just a method that returns false if any of those IDs does not exists in my database, and returns true if all of those exists.

It looked easy initially, but I didn't find a way to return that result from my database directly using EF Core. I always need to compare the Count of my query result with my list Count.

My better approach was:

public async Task<bool> IsIdListValid(IEnumerable<int> idList) =>
   (await _context.Foo
              .Select(x => x.Id)
              .CountAsync(id => idList.Contains(id))
   ) == idList.Distinct().Count();

So, what I'm asking is: there is a better way to write that query, more readable and performant?

1
0
5/7/2018 10:09:36 PM

Accepted Answer

What you are looking for is All:

public async Task<bool> IsIdListValid(IEnumerable<int> idList)  
{
   var validIds = await _context.Foo.Select(x => x.Id).ToListAync();
   return idList.All(x => validIds.Contains(x));
}
2
5/7/2018 10:17:21 PM

Popular Answer

Instead of verifying by count, you can implement your question directly:

public async Task<bool> IsIdListValid(IEnumerable<int> idList) =>
    idList.Any(id => !_context.Foo.Any(f => f.id == id));

This will send on SQL query per member of idList when it is valid. If idList is short, this might be okay, otherwise your Count query is probably best, though the Select isn't needed. This will shortcut however if idList contains an invalid member, stopping on the first invalid member.

Another possiblity is using the EntityFrameworkCore.MemoryJoin extension that adds the ability to send an in-memory list using SQL VALUES and then join to it.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow