Hey i have list of integers which are id's. I want to create async method that returns list of id's that are not present in dbContext table. I have something like this.
public async Task<List<int>> NotExisting(List<int> inputIds, CancellationToken cancellationtoken)
{
var notExisting = await _dbContext.Table
.Where(x => !inputIds.Contains(x.Id)).Select(x => x.Id).ToListAsync();
return notExisting;
}
Now its just taking all of the elements in table that doesnt match the input id. I want to only get the elements from inputIds
that are not present in _dbContext.Table
. I know i am taking wrong thing in Select
but i dont know how to access the current id in inputIds
.
CodePudding user response:
You just need to switch the SELECT
source, since the IDs you want to have are ultimately NOT coming from the database:
var allIDsInDb = (await _dbContext.Table.Select(x => x.Id).ToListAsync()).ToHashSet();
// ToHashSet() was for faster lookups in the next line
var notExisting = inputIds.Except(allIDsInDb).ToList();
UPD: If you don't want to pull all the IDs from the database, you still need to find out which IDs from your list DO exist in the db, so just add a condition:
var allIDsInDb = (await _dbContext.Table.Where(x => inputIds.Contains(x.Id)).Select(x => x.Id).ToListAsync()).ToHashSet();
// ToHashSet() was for faster lookups in the next line
var notExisting = inputIds.Except(allIDsInDb).ToList();