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())
{
Cities.AddRange(
new City{Name = "New York"},
new City{Name = "Seattle"},
new City{Name = "San Francisco"});
SaveChanges();
}

}

Now, we just call it from the Program.Main method:

public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetService<GiveNTakeContext>();
try
{
context.Database.Migrate();
context.SeedData();
}
catch (Exception ex)
{
// Error handling
}
}
}

You have now completed all the necessary steps for creating and connecting to a database with EF Core, and supporting automatic migrations. Next, you'll learn how to save and query the data in your database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.152.159