July 02, 2016 by Anuraj Estimated read time : 5 mins
ASP.NET CorePostgreSQLEF Migration
This post is about using PostgreSQL with ASP.NET Core. PostgreSQL is an object-relational database management system (ORDBMS) with an emphasis on extensibility and standards-compliance. Recently in ASP.NET Forums, someone asking about using postgresql with ASP.NET Core. Since I don’t have an installed version available, I thought I will use postgresql as a service version from elephantsql.com. They are offering a free tier postgresql database. You can register yourself and can create databases. In this post I am using EF Migrations for creating databases. So I am using a ASP.NET Core Web API project, I have created a API project with ASP.NET YO Generator. To connect to postgresql server, you require “Npgsql.EntityFrameworkCore.PostgreSQL” nuget package, and for EF migrations you require “Microsoft.EntityFrameworkCore.Tools” package. Here is the project.json file.
Now it is time to create Model classes and DbContext classes. I am using a simple book model. Here is the Model class and DbContext class.
Now you can execute “dotnet restore” command to download all the required packages. Once restore successfully completed, you can modify the startup.cs, ConfigureServices method to set the database provider and connection string.
Now you can create migration scripts using “dotnet ef migration” command.
Here is the output of “dotnet ef migrations add Initial” command. I am creating a migration script named “Initial”.
Once migration created, you can update database using update command.
And here is my controller implementation, which is pretty straight forward. DbContext is getting injected to the controller, and I am using DbContext directly.
And here is the screenshot of the data inserted to ElephantSQL Console.