Esempio n. 1
0
        public static async Task <int> SeedDatabaseIfNoBooksAsync(this EfCoreContext context, string dataDirectory)
        {
            var numBooks = context.Books.Count();

            if (numBooks == 0)
            {
                //the database is empty so we fill it from a json file
                var books = BookJsonLoader.LoadBooks(Path.Combine(dataDirectory, SeedFileSubDirectory),
                                                     SeedDataSearchName).ToList();
                context.Books.AddRange(books);
                await context.SaveChangesAsync();

                //We add this separately so that it has the highest Id. That will make it appear at the top of the default list
                context.Books.Add(SpecialBook.CreateSpecialBook());
                await context.SaveChangesAsync();

                numBooks = books.Count + 1;
            }

            return(numBooks);
        }
Esempio n. 2
0
        public static int SeedDatabase(this DataContext context, string dataDirectory)
        {
            if (!(context.GetService <IDatabaseCreator>() as RelationalDatabaseCreator).Exists())
            {
                throw new InvalidOperationException("The database does not exist. If you are using Migrations then run PMC command update-database to create it");
            }

            var numBooks = context.Books.Count();

            if (numBooks == 0)
            {
                //the database is emply so we fill it from a json file
                var books = BookJsonLoader.LoadBooks(Path.Combine(dataDirectory, SeedFileSubDirectory), SeedDataSearchName).ToList();
                context.Books.AddRange(books);
                context.SaveChanges();
                //We add this separately so that it has the highest Id. That will make it appear at the top of the default list
                context.Books.Add(SpecialBook.CreateSpecialBook());
                context.SaveChanges();
                numBooks = books.Count + 1;
            }

            return(numBooks);
        }