C#C
C#15mo ago
79 replies
Pilvinen

Trying to learn EF Core

Am I doing this correctly?

public static void SaveData(ConfigurationData dataToSave) {

    // Open a connection to the database and save the data.
    using (var gameDatabaseConnection = new DatabaseConnection(Paths.GetGameDatabaseFilePath())) {

        ConfigurationData search = gameDatabaseConnection.Find<ConfigurationData>(dataToSave.PlayerProfileId);
        if (search is null) {
            // If the configuration data doesn't exist, create a new one.
            gameDatabaseConnection.ConfigurationDataSets.Add(dataToSave);
        } else {
            // If the configuration data exists, update it.
            gameDatabaseConnection.ConfigurationDataSets.Update(dataToSave);
        }

        // Save the changes to the database.
        gameDatabaseConnection.SaveChanges();

        // Update the cache with the new data. Updating inside the connection ensures the cache is
        // always up-to-date with the database. If the database operation fails, the cache won't be updated.
        Cache[dataToSave.PlayerProfileId] = dataToSave;
    }
}
image.png
Was this page helpful?