This section updates the data initializer for the changes to the StoreContext and to support dependency injection.
- [Instructor] In this section, we'll migrate the data initializer. Now data initializers were done very differently in EF6. They were base classes you could derive from such as drop and create database if model changes. Those have not moved forward with EF Core. You have to roll your own. Now I've done that for you in the Web API 2.2 version just to save a whole lot of typing. We are going to copy those in. Then we have to tweak them to support dependency injection and the changes made to the store context.
Once again, we will drag the Initializer folder over to the EF directory. That adds them all in. We can delete the DataInitializer. Then let's look at the Initializer and what it does. There's one method that is really the only one that matters. That is the InitializedData. It's two flavors, one that creates a new StoreContext, one that uses a passed in StoreContext.
ClearData just deletes the records and resets the identity. Seed adds data in. Only a couple of changes we have to make to these. In the Initializer itself, we're going to add using statements for EntityFrameworkCore and the DependencyInjection framework so using Microsoft.EntityFrameworkCore and using Microsoft.Extensions .DependencyInjection.
We will create a method here, public static void also called InitializedData. As a parameter, we're going to take an IserviceProvider that comes from the DependencyInjection namespace. We'll call the parameter serviceProvider.
Then we will Get the context from the serviceProvider. Then we can just call InitializedData passing in that context. We need to make one change to the SampleData class. A whole bunch of methods to return data to save you a bunch of typing and are useful for populating a database for testing.
We're going to switch out System.Data.Entity with Microsoft.EntityFrameworkCore. Those are all the changes we need to make for the data initializers.
- Creating the .NET Core project
- Adding Entity Framework
- Migrating the data access layer (DAL)
- Configuring services and the HTTP pipeline
- Adding remaining services to the dependency injection container
- Migrating controllers and actions
- Testing the services