In my previous posts, I showed you how to create an Entity Framework Core version of Northwind. While it was a good example of reverse engineering a data model including entity classes from an existing database, I wasn’t entirely happy with the resulting solution. It depended on Transact-SQL and this meant that the solution was dependent on Microsoft SQL Server. The resulting solution was not suitable for use with other database providers.
In order to remove the dependency on the T-SQL scripts, I have created a new database initializer that is responsible for ensuring that the database has been created and for populating the database with sample data. You can view the initializer here (be warned, it’s 1.43 MB).
The initializer works as follows:
- Within the NorthwindTraders project, Startup.cs has been modified to include the following statement in the Configure method:
This statement launches the initializer on application start-up.
- Within the NorthwindInitializer.Initialize method, the following line ensures that the database has been created:
- Next, a check is made to verify if the database already has data:
if (context.Customers.Any()) return; // Db has been seeded
- Finally, the initializer seeds all tables, including Customers, Employees, Categories, Suppliers, Products, Orders, and so on.
In addition to the above changes, I’ve tidied up the solution by removing the unnecessary T-SQL scripts and associated migrations. I’ve also refactored the code base to ensure that it is as clean as possible. Check out Northwind Traders on GitHub to view the source code along with the getting started instructions.