Пример #1
0
        public static async Task Initialize(NoveltyContext context, ILogger logger, CancellationToken cancellationToken = default)
        {
            try
            {
                await context.Database.EnsureCreatedAsync(cancellationToken);
            }
            catch (Exception ex)
            {
                throw new CouldNotConnectToDbException(
                          "Unable to connect to database. Ensure the provided connection string is valid and database is responding.",
                          ex);
            }

            logger.LogInformation("Preparing for database initialization..");

            if (context.Novelties.Any())
            {
                logger.LogInformation("Database has been already fed, skipping initialization..");
                return;
            }

            var novelties = new[]
            {
                new Novelty
                {
                    Name        = "first", Version = 1, Created = new DateTime(2020, 01, 01, 12, 0, 0),
                    Description = LoremIpsum, LastChanged = DateTime.UtcNow
                },
                new Novelty
                {
                    Name        = "second", Version = 1, Created = new DateTime(2020, 01, 02, 12, 0, 0),
                    Description = Cicero, LastChanged = DateTime.UtcNow
                },
                new Novelty
                {
                    Name        = "third", Version = 1, Created = new DateTime(2020, 01, 03, 12, 0, 0),
                    Description = Kafka, LastChanged = DateTime.UtcNow
                }
            };

            var fillerNovelties = Enumerable.Range(1, 100).Select(x => new Novelty
            {
                Name        = $"filler novelty {x}", Version = 1, Created = new DateTime(1900, 01, 01),
                LastChanged = DateTime.UtcNow, Description = "some boring description"
            });

            foreach (var novelty in novelties.Concat(fillerNovelties))
            {
                await context.Novelties.AddAsync(novelty, cancellationToken);
            }

            await context.SaveChangesAsync(cancellationToken);

            logger.LogInformation("Database has been initialized");
        }
Пример #2
0
 public NoveltyRepository(NoveltyContext context)
 {
     _context = context;
 }