March 17, 2018

Simple data localisation with .NET core – Part 2 – Add models, database and migrations with code first

This tutorial will take you through setting up a data localisation project from scratch using iQuarc.DataLocalization. Full source can be found on github.

  1. Set up basic .NET core MVC project
  2. Models, database and migrations with code first
  3. API Controller to view model data
  4. Data localisation for models using iQuarc.DataLocalization

We will be using a simple domain of a taking a Course and each Course consists of many Skills. Both Course and Skill data needs to be localised to different languages. We will keep the models super simple and only give them a Title and Name property.

This is the second part. If you already know about models, migrations and controllers, move on to part 4: Add data localisation for models using iQuarc.DataLocalization. If you need to set up a new project you can see part 1: Set up basic .NET core MVC project.

Add models, database and migrations

1. Create a folder in your project to hold your models, I named mine Models

2. Create models for Course and Skill

3. Create a folder to hold your DbContext that is used to access data, I named mine Data

4. Create a DbContext in your data folder, I named mine ApplicationDbContext

5. Configure your database and DbContext in Startup.cs

Now we can enable migrations and create the database

6. Open Package Manager and add your migration with any name, I will use “init”

This should generate a new Folder “Migrations” in your project together with a migration class.

7. Apply the migration to the database with the following command

This should create a database for you with the name defined in the connection string in Startup.cs. I named ming “iQuarcPoc”.

8. To add some data to the database we create a static class that holds our data, I named mine DataInitializer

9. Call the data initialzer from your Main method in Program.cs

10. Run your application and you should be able to see the database seeded using the SQL Server Object Explorer in Visual Studio

Great work! In the next step we add an API controller to fetch our data. Check out part 3: Add API Controller to view model data