Adding seed data

After the database has been created or migrated to a new schema, the new tables will be empty. Many times, you will need to add initial data that your application relies on. For example, the categories and locations in the GiveNTake application are predefined, and so we would like to add them when the database is created. To add the initial values, we must add a new method to the GiveNTakeContext (usually named SeedData()) and execute it after the migration has finished:

public void SeedData(){    if (!Categories.Any())    {        var appliances=new Category()        {            Name = "Appliances",            Subcategories = new List<Category>()            {                new Category(){Name = "Microwaves"}            }        };        Categories.Add(appliances);                ...                SaveChanges();    }    if (!Cities.Any())    {

Get Hands-On Full-Stack Web Development with ASP.NET Core now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.