Exemple #1
0
        /// <summary>
        ///     Initializes the database, if the db is empty this method will build a model to seed it.
        /// </summary>
        /// <param name="context">The context to be initialized.</param>
        /// <param name="logger">Where to log any issues.</param>
        public static void Initialize(NOContext context, ILogger logger)
        {
            string root = Path.Combine("Data", "Countries", "NO");

            if (!DatabaseIsReady(context))
            {
                return;
            }

            // Catch all Argument/KeyNotFound/CsvFileFormatExceptions thrown by model validation
            try
            {
                // Parse all DistrictMetrics
                IEnumerable <DistrictMetrics> districtMetrics = ParseDistrictMetrics(root).ToList();
                context.DistrictMetrics.AddRange(districtMetrics);

                root = Path.Combine(root, "PE");

                // Parse all PartyVotes
                Dictionary <int, List <ResultFormat> > resultFormats = ParseResultFormat(root);
                List <PartyVotes> partyVotes = ParsePartyVotes(resultFormats, "PE").ToList();
                context.PartyVotes.AddRange(partyVotes);

                // Create list of all parties
                List <Party> parties = ParseParties(resultFormats).ToList();
                context.Parties.AddRange(parties);

                // Sum the total number of votes cast in an election
                IReadOnlyDictionary <int, int> yearTotalVotesMap = SumTotalVotes(partyVotes);

                // Parse all ElectionParameters
                List <ElectionParameters> electionParameters = ParseElectionParameters(root, yearTotalVotesMap).ToList();
                context.ElectionParameters.AddRange(electionParameters);

                context.SaveChanges();
            }
            catch (ArgumentException argumentException)
            {
                logger.LogError(argumentException, "The data results in an illegal model and could not be built.");
            }
            catch (KeyNotFoundException keyNotFoundException)
            {
                logger.LogError(keyNotFoundException,
                                "The directory name does not match any ID in the dictionary.");
            }
            catch (CsvFileFormatException csvFileFormatException)
            {
                logger.LogError(csvFileFormatException, "The csv file has a malformed format.");
            }
        }
Exemple #2
0
 /// <summary>
 /// Check whether the DB is ready and empty
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 private static bool DatabaseIsReady(NOContext context)
 {
     context.Database.EnsureCreated();
     return(!context.PartyVotes.Any());
 }