Code: Northwind Traders with Entity Framework Core

In my previous posts, I showed you how to create an Entity Framework Core version of Northwind. It was a good example of reverse engineering a data model including entity classes from an existing database. Did you notice that it depended on Transact-SQL and that this meant that the solution was dependent on Microsoft SQL Server? Therefore the resulting solution was not suitable for use with other database providers.

Now let’s improve this solution.

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:

  1. 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.
  2. Within the NorthwindInitializer.Initialize method, the following line ensures that the database has been created:
  3. Next, a check is made to verify if the database already has data:
    if (context.Customers.Any()) return; // Db has been seeded
  4. Finally, the initializer seeds all tables, including Customers, Employees, Categories, Suppliers, Products, Orders, and so on.

Check out Northwind Traders on GitHub – view the source code along with the getting started instructions.