Home > Blockchain >  Get missing values from database check
Get missing values from database check

Time:12-17

As part of an application I have developed there are certain checks that are done to see if the necessary data is available in the database. This is done through the following functions:

    private void GetDataAndValidate(string connection, List<string> AdpTitles, List<string> OwnershipRoles)
    {
        var repo = new RecordRepository(connection);

        var adpTitlesInDb = repo.GetAdvancedProperties()
            .Where(i => i.Enabled)
            .Select(i => i.Title)
            .ToList();

        var roleTitlesInDb = repo.GetOwnershipRoles()
            .Select(i => i.Title)
            .ToList();

        var areADPsValid = ValidateTitles(adpTitlesInDb, AdpTitles);

        if (areADPsValid is not false)
            _log.Information("Properties found");
        else
            LogErrors("Warning", "Not all properties found in the database");


        var areRoleTitlesValid = ValidateTitles(roleTitlesInDb, OwnershipRoles);

        if (areRoleTitlesValid is not false)
            _log.Information("Roles found");
        else
            LogErrors("Warning", "Not all roles found in database");
    }

The ValidateTitles function is:

    private static bool ValidateTitles(List<string> TitlesInDb, List<string> TitlesToCheck)
    {
        foreach (var title in TitlesToCheck)
        {
            if (!TitlesInDb.Contains(title, StringComparer.InvariantCultureIgnoreCase))
                return false;
        }

        return true;

    }

This works fine however, I'm wanting to change it so the warning message is more meaningful than just something like:

LogErrors("Warning", "Not all properties found in the database");

I'm trying to get it changed so that the message will say exactly which property is missing, how can I go about doing that?

CodePudding user response:

How about something like:

private static bool ValidateTitles(List<string> TitlesInDb, List<string> TitlesToCheck, out string[] missingTitles)
{
    missingTitles = TitlesToCheck
            .Except(TitlesInDb, StringComparer.InvariantCultureIgnoreCase)
            .ToArray();
  
    return missingTitles.Length == 0;
}

And then call it like:

var areADPsValid = ValidateTitles(adpTitlesInDb, AdpTitles, out var missingTitles);

if (areADPsValid)
    _log.Information("Properties found");
else
    LogErrors("Warning", "Not all properties found in the database, missing: "   string.Join(", ", missingTitles));

  •  Tags:  
  • c#
  • Related