Example #1
0
        private static void SetupDatabase()
        {
            using (var db = new BloggingContext())
            {
                if (db.Database.EnsureCreated())
                {
                    db.Blogs.Add(
                        new Blog
                    {
                        Name  = "Fish Blog",
                        Url   = "http://sample.com/blogs/fish",
                        Posts = new List <Post>
                        {
                            new Post {
                                Title = "Fish care 101"
                            },
                            new Post {
                                Title = "Caring for tropical fish"
                            },
                            new Post {
                                Title = "Types of ornamental fish"
                            }
                        }
                    });

                    db.Blogs.Add(
                        new Blog
                    {
                        Name  = "Cats Blog",
                        Url   = "http://sample.com/blogs/cats",
                        Posts = new List <Post>
                        {
                            new Post {
                                Title = "Cat care 101"
                            },
                            new Post {
                                Title = "Caring for tropical cats"
                            },
                            new Post {
                                Title = "Types of ornamental cats"
                            }
                        }
                    });

                    db.Blogs.Add(
                        new Blog
                    {
                        Name  = "Catfish Blog",
                        Url   = "http://sample.com/blogs/catfish",
                        Posts = new List <Post>
                        {
                            new Post {
                                Title = "Catfish care 101"
                            },
                            new Post {
                                Title = "History of the catfish name"
                            }
                        }
                    });

                    db.SaveChanges();

                    #region View
                    db.Database.ExecuteSqlRaw(
                        @"CREATE VIEW View_BlogPostCounts AS 
                            SELECT b.Name, Count(p.PostId) as PostCount 
                            FROM Blogs b
                            JOIN Posts p on p.BlogId = b.BlogId
                            GROUP BY b.Name");
                    #endregion
                }
            }
        }