I'm developing an application that needs to take in a list of objects and validate their properties against database values to ensure everything is valid. However, there can be many objects with many properties that need validation.
My initial idea was to create a helper method for each validation operation, each one opening a connection to the Database Context, performing their required select statements, and then returning the appropriate data.
The final operation within the foreach loop would be to await all of the operations, and then move onto the next object.
However, my initial attempts to use FirstOrDefaultAsync have proven futile as it never seems to return a value, and it doesn't seem compatible with Linq to SQL. So what other options do I have to make these helper methods asynchronous?
My main method looks something like this:
public async Task<List<BulkUserResponse.VerifiedUser>> ValidateBulkUsers(BulkUserResponse userList)
{
var users = userList.UserList;
foreach (var user in users)
{
var userGlobalLogin = VerifyGlobalLogin(user.GlobalLogin);
// other variables and helper methods
await Task.WhenAll(userGlobalLogin);
user.GlobalLogin = userGlobalLogin.Result;
// other properties and helper method assignment
}
return users;
}
With one of the helper methods looking like this:
public async Task<BulkUserResponse.GlobalLogin> VerifyGlobalLogin(BulkUserResponse.GlobalLogin login)
{
using (var context = new DbContext())
{
var userExists = await context.GlobalLogins.FirstOrDefaultAsync(n => n.LoginName == login.Value) == null;
login.Valid = userExists;
login.VerificationMessage = (userExists ? "" : "Login already exists.");
return login;
}
}
Initially the helper method looked like:
public async Task<BulkUserResponse.GlobalLogin> VerifyGlobalLogin(BulkUserResponse.GlobalLogin login)
{
using (var context = new DbContext())
{
var userExists = context.GlobalLogins.FirstOrDefault(n => n.LoginName == login.Value) == null;
login.Valid = userExists;
login.VerificationMessage = (userExists ? "" : "Login already exists.");
return login;
}
}