WebAPI with .Net Core and Postgres in Visual Studio Code

In this tutorial, you use Entity Framework Core and Postgres to create the simplest web service application in Visual Studio Code.

Create the project

dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL --version 2.1.0
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL --version 2.1.0dotnet add package NpgSql.EntityFrameworkCore.PostgreSQL.Design

Add a model class

namespace TodoApi.Models {     public class TodoItem   
{        
 
public long Id { get; set; }        
public string Name { get; set; }         
public bool IsComplete { get; set; }       }
}

Create the database context

using Microsoft.EntityFrameworkCore;  
namespace TodoApi.Models {     
public class TodoContext : DbContext     
  {         
    public TodoContext(DbContextOptions<TodoContext> options)                            : base(options)         
{         
}       
    public DbSet<TodoItem> TodoItems { get; set; }     
  
   } 
}

Register the database context

using TodoApi.Models;namespace TodoApi{public class Startup{public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){// Add framework services.services.AddDbContext<TodoContext>(options =>options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IHostingEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{app.UseHsts();}app.UseHttpsRedirection();app.UseMvc();}}}

Change Connection String

"ConnectionStrings": {"DefaultConnection":"Host=localhost;Port=5432;Username=postgres;Password=password;Database=TodoList;"}

Run database Migration

output of dotnet ef migrations add initial
Migrations folder
output of database update in terminal
Database & Tables in PostgreSQL

Add a controller

using Microsoft.AspNetCore.Mvc; 
using System.Collections.Generic; 
using System.Linq; 
using TodoApi.Models;  
namespace TodoApi.Controllers {     
[Route("api/[controller]")]     
[ApiController]     
public class TodoController : ControllerBase     
{        
private readonly TodoContext _context;          public TodoController(TodoContext context)         
{             _context = context;              
if (_context.TodoItems.Count() == 0)             
{                 
_context.TodoItems.Add(new TodoItem { Name = "Item1" });                 _context.SaveChanges();             
}         
}            
} 
}

Get to-do items

[HttpGet] 
public ActionResult<List<TodoItem>> GetAll() 
{     
return _context.TodoItems.ToList(); 
} 
 
[HttpGet("{id}", Name = "GetTodo")] 
public ActionResult<TodoItem> GetById(long id) 
{    
var item = _context.TodoItems.Find(id);     
if (item == null)    
{         
return NotFound();     
}     
return item; 
}

Routing and URL paths

namespace TodoApi.Controllers 
{     
[Route("api/[controller]")]     
[ApiController]     
public class TodoController : ControllerBase     
{         
private readonly TodoContext _context;
TodoController
[HttpGet(“{id}”, Name = “GetTodo”)] 
public ActionResult<TodoItem> GetById(long id) 
{ 
var item = _context.TodoItems.Find(id); 
if (item == null) 
{ 
return NotFound(); 
} 
return item; 
}

Return values

Launch the app

[   
{     "id": 1,     
"name": "Item1",     
"isComplete": false   
} 
]
Response of http://localhost:5002/api/todo in browser
View Data of TodoItems table
[   
{     "id": 2,     
"name": "Item1",     
"isComplete": false   
} 
]

Where to Go From Here?

Comments