1. Introduction
This article will walk you through on building a simple web API service using .NETCore. Service is extended to interact with a SQL server database in a windows PC and then modify the same service to work with a MYSQL database in a Linux server.
2. Background
3. Prerequisites
In this article, we are working with two environments, Windows and a Linux environment. Check whether you have installed these prerequisites before you start.
In Windows environment,
In Linux environment,
I have used Entity framework Core to access data from databases, necessary references to EFCore is installed in next steps.
4. Create a Web API application in .NETCore
Let’s try to create a .NETCore application from Visual Studio 2015
Create a new project from Visual Studio 2015, In .NETCore tab, select ASP.NET Core Web Application (.NET Core) . Give it a name and click on OK.
Select Web API from ASP.NET Core templates and click on OK.
Check folder structure of the application, It includes a Program.cs and Startup file. It includes a project.json file to define all required packages for your application. appsettings.json file maintains application settings same as web.config file in a
ASP.NET Web application. Controllers folder has all Web API Controllers.
4.1. Open service application from Visual Studio Code.
cd into the application directory and open Visual Studio Code using code . command. You can see folder structure of your application as above. Add assets to build and debug your application as the info dialog box suggests.
vscode folder is added into the solution with launch.json and tasks.json file.
4.2. Dependencies in project.json file
Let’s see what are the dependencies required for a mvc application.
Since We create a Web API application, in project.json file, It shows Microsoft.AspNetCore.Mvc package dependency.
4.3. Run ValuesController and check service calls.
Let’s run Web API application and check available services.
Build (Ctrl + Shift + b) and run (Ctrl + F5) your application and ping to the Read service as above. Its shows return values in the browser.
4.4. Let’s build the movie service
In this solution, Movie service is accessing a SQL Server database on windows, and later the same application with less modifications, going to access a MYSql server database in a Linux server
4.4.1. Create Movie model
namespace
movieStore.Models
{
public
class
Movie
{
public
int
ID {
get
;
set
; }
public
string
Title {
get
;
set
; }
public
string
Director {
get
;
set
; }
public
int
Year {
get
;
set
; }
public
string
Language {
get
;
set
; }
}
}
Create a Model folder to define entities in your application. Then create Movie class and add properties into it. We follow Code First approach in this example. So when we create the database Movie table will be created.
4.5. Create Movie service with SQL server on Windows.
4.5.1. Create Context class to build the database.
namespace
movieStore.Models
{
public
class
MovieDbContext : DbContext
{
public
MovieDbContext(DbContextOptions<MovieDbContext> options) :
base
(options)
{
}
public
DbSet<Movie> Movies {
get
;
set
; }
}
}
From context class, our database will be generated. Context class should be inherited from DbContext class. In order to do that, we have to add references from Entityframework core.
4.5.2. Install Entityframework Core (EF Core)
Add entityframeworkcore reference as a dependency into project.json file, “Microsoft.EntityFrameworkCore”: “1.0.0” and resolve reference error in MovieDbContext class by adding using Microsoft.EntityFrameworkCore statement.
4.5.3. Define the connectionstring
Define the connectionstring in appsettings.json file to connect to the Sql server,
“ConnectionStrings: { “DefaultConnection”: “Data Source=localhost;Initial Catalog=movieDB;Integrated Security=
true
” }
4.5.4. Check MovieDbContext class
In MovieDbContext class, define constructor with context options and call base class method.
4.5.5. Add entities in moviecontext class
Try to run migrations for MovieDbContext class,
dotnet ef migrations add InitialMigration
It gives an error,
No executable found matching command “dotnet-ef”
We have to install entityframeworkcore tools to run migrations from .NET cli. Let’s try to do that.
4.5.6. Add EFCore tools
Add EFCore tools in tools section of project.json,
"Microsoft.EntityframeworkCore.Tools" : "1.0.0-preview2-final"
Try to run migration and it gives an error again!!,
Could not invoke this command with the startup project ‘demo’. Check that ‘Microsoft.EntityFrameworkCore.Design’ has been added to “dependencies” in the startup project and that the version of ‘Microsoft.EntityFrameworkCore.Tools’ in “tools” and ‘Microsoft.EntityFrameworkCore.Design`
are the same. See
http://go.microsoft.com/fwlink/?LinkId=798221 for more details,
We haven’t added EFCore Design as a reference, We have to add EFCore Design references to run migrations scripts. Let’s add it and check. And also it mentions ‘Microsoft.EntityFrameworkCore.Design’ and ‘Microsoft.EntityFrameworkCore.Tools’ version should
be same.
4.5.7. Add EFCore Design reference.
Add EFCore Design reference into project.json file. Note that, `Microsoft.EntityFrameworkCore.Design' and `Microsoft.EntityFrameworkCore.Tools' version are same.
"Microsoft.EntityFrameworkCore.Design": "1.0.0-preview2-final"
Then try to run migrations command again and it gives another error,
No parameterless constructor was found on ‘MovieDbContext’. Either add a parameterless constructor to ‘MovieDbContext’ or add an implementation of ‘IDbContextFactory‘ in the same assembly as ‘MovieDbContext’.
4.5.8. Startup class implementation
public
void
ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MovieDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString(
"DefaultConnection"
)));
//
Add framework services
services.AddMvc();
}
In Configure services method, it’s going to add some services into the application.
services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”)));
Add the database context and define the connectionstring of your database, in configure service method, it’s missing some references, since we haven't add any EntityframeworkCore sqlserver references.
4.5.9. Add EFCore Sqlserver references
Add EFCore Sql server reference in project.json file and restore them.
“Microsoft.EntityFrameworkCore.SqlServer”: “1.0.0”
Now sqlserver reference is added. Configure service method looks fine.
4.5.10. Run Migrations
Let’s create movieDB in sql server.
Run Sqlserver migrations, It doesn’t give any errors in .NET CLI, Migrations folder is created with migrations scripts. In Initial Migration class, it defines Up and Down methods to create and drop movie table respectively.
4.5.11. Update the database
run commands to update the database. In sqlserver, movieDB got created.
dotnet ef database update
4.5.12. Add Movie controller
In Visual studio code, We can’t use scaffolding. So i created a Movie Controller with all the CRUD operations of Movie entity in visual studio. Let’s add it.
In Movie Controller, it works with application/json type data, and the route is api/Movies. Note that in .NET Core Api controllers inherit from Controller class, not from API Controller class.
Go to api/movies method and check Network tab in developer tools. method returns 200 - OK. as a response. We don’t have data in movie database, Let’s try to add some data.
4.5.13. Add data using Postman
Postman is a tool to test your service apis. Although we can test GET requests through browser, to test POST requests, we need to use Postman. Add a movie using Postman and retrieve it using web browser.
We have created a service API using .NETCore and SQLServer. Let’s try to run this same application on Ubuntu with MySQL.
4.6. Change Movie service to work with MYSQL on Linux server.
4.6.1. Clone your application in Ubuntu
Let’s try to open your application in Ubuntu, We are going to connect this application to MySQL server,
Type git clone … with repository url, Your project will be downloaded. Then cd into application directory and open it in visual studio code.
4.6.2. Restore packages and build your application
Restore packages defined in project.json file and Build your application. It all works fine.
4.6.3. Let’s try to run the application
Let’s try to run our application without any modifications, It seems working fine. Let’s navigate to api/values , It calls READ service of Values service. It returns 200 - OK as response.
Ping to api/movies, it returns an empty array, since we don’t have a database.
Check the terminal and try to find any errors, It shows a fail error in red. It says 'Microsoft.EntityFrameworkCore.Query.Internal.SqlServerQueryCompilationContextFactory[1] An exception occurred in the database while iterating the results of a query. System.NotSupportedException:
The keyword ‘integrated security’ is not supported on this platform. at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) …'
It says an error as The keyword ‘integrated security’ is not supported on this platform. If you remember, where we have used integrated security , that’s in sql server connectionString. We can’t operate with Sql server on Ubuntu. We have to install My SQL
server to store data in your application. Let’s do that.
4.6.4. Add MySQL connectionString
Add mysql connectionString in appsetings.json file, movieDB will get created in mysql server.
"DefaultConnection" : "server=localhost;database=movieDB;uid=root;pwd=hansamali;sslmode=none;"
4.6.5. Add MySQL service in your application
If you remember, we added Sql service into the application when we run in Windows. In Ubuntu also same thing we have to do. Add MySQL service into your application with dbContext class. But it seems we are missing something in here.
Note that, Microsoft.EntityframeworkCore has been highlighted. Your application doesn’t use that reference anymore. It’s a reference from Sql server. We have to add a reference from MySQL to proceed with this. Let’s try to add it.
Add MySQL EFCore reference in project.json file and restore it.
“MySql.Data.EntityFrameworkCore” : “7.0.4-ir-191”
Add necessary changes in ConfigureServices method in Startup class.
services.AddDbContext(options =>
options.UseMySQL(Configuration.GetConnectionString(“DefaultConnection”)));
Add necessary using statements in startup class.
using
MySQL.Data.EntityFrameworkCore.Extensions;
In windows with Sql server, We run migration scripts and ensure database is created. But with Ubuntu, we can’t do that. Somehow we have to ensure our database is created. Let’s give it a try.
4.6.6. Ensure MySQL database got created
Add this lines of code to ensure MySQL database got created.
var optionsBuilder =
new
DbContextOptionsBuilder();
optionsBuilder.UseMySQL(Configuration.GetConnectionString(“DefaultConnection”));
var context =
new
MovieDbContext(optionsBuilder.Options);
context.Database.EnsureCreated();
4.6.7. Run your application
Then build and run the application, navigate to movies read service and verify it works fine. read service returns empty array. Let’s check database is created in MySQL server.
4.6.8. View MySQL databases
run commands to access mysql shell,
type command to view all the available databases, you can see movieDB is successfully created.
4.6.9. Let’s add some data into Movie database in MySQL
Call POST service in movie controller and add a movie into the mysql database. Refresh read movie service, it shows available movies in your mysql database.
Connect to the mysql shell and try to view data in Movies table.
Go to mysql shell by typing this command,
view available databases
type following command to go inside a database and query it
You can see available tables in movieDB using this command
Type a select query to view data in movies table
In this post, I described how to run a web api application in windows with Sqlserver. And then we tried to configure same service application on Ubuntu with MySql server, with less amount of coding we could achieve that. It was a really cool feature in .NETCore
5. Download
5.1. TechNet Gallery
5.2. GitHub
6. Conclusion
In this article as you saw, we could modify same .NETCore application in both environments, Windows and Linux. We worked with two different databases SQL server and MYSQL, with Entityframework Core. I hope EFCore will provide its features for Oracle soon.
Since .NETCore is cross platform and open source building applications for multiple environments is possible today.
7. References