.Net + MySQL + Vue.js 3 CRUD Application Example

In this section, we will learn how to develop a full-stack web application that is a basic User Management Application using .Net 6MySQLPomelo Entity Framework Core provider for MySQL, and Vue.js 3. You could download the source code from our Github repository, the download link is provided at the end of this tutorial.


After completing this tutorial what we will build?

We will build a full-stack web application that is a basic User Management Application with CRUD features: 

• Create User 
• List User 
• Update User 
• Delete User


We divided this tutorial into two parts. 

PART 1 - Restful API Development with .Net 6 & MySQL database.
PART 2 - UI development using Vue.js 3.


PART 1 - Restful API Development with .Net 6 & MySQL database.

These are APIs that .Net backend App will export:


Create database and table.

First, you need to create a database in the MySQL server. 
CREATE DATABASE testdb;


Create table:
CREATE TABLE users(
 id INT PRIMARY KEY AUTO_INCREMENT,
 first_name VARCHAR (20) NOT NULL,
 last_name VARCHAR (20) NOT NULL,
 email VARCHAR (20) NOT NULL
);


Project directory:


User Entity

Path: /Entities/User.cs

The user entity class represents the data stored in the database for users.

namespace WebApi.Entities;

using System.Text.Json.Serialization;

public class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
 
}


App Exception

Path: /Helpers/AppException.cs

The app exception is a custom exception class used to differentiate between handled and unhandled exceptions in the .NET API. Handled exceptions are generated by application code and used to return custome error messages.

namespace WebApi.Helpers;

using System.Globalization;

public class AppException : Exception
{
    public AppException() : base() {}

    public AppException(string message) : base(message) { }

    public AppException(string message, params object[] args)
        : base(String.Format(CultureInfo.CurrentCulture, message, args))
    {
    }
}


AutoMapper Profile

Path: /Helpers/AutoMapperProfile.cs

AutoMapper is an object mapper that helps you transform one object of one type into an output object of a different type. This type of transformation is often needed when you work on business logic. In this example we're using it to map between User entities and a couple of different model types - CreateRequest and UpdateRequest.

namespace WebApi.Helpers;

using AutoMapper;
using WebApi.Entities;
using WebApi.Models.Users;

public class AutoMapperProfile : Profile
{
    public AutoMapperProfile()
    {
        // CreateRequest -> User
        CreateMap<CreateRequest, User>();

        // UpdateRequest -> User
        CreateMap<UpdateRequest, User>()
            .ForAllMembers(x => x.Condition(
                (src, dest, prop) =>
                {
                    // ignore both null & empty string properties
                    if (prop == null) return false;
                    if (prop.GetType() == typeof(string) && string.IsNullOrEmpty((string)prop)) return false;

                    return true;
                }
            ));
    }
}


Data Context

Path: /Helpers/DataContext.cs

The primary class that is responsible for interacting with data as objects is the DbContext. The recommended way to work with context is to define a class that derives from the DbContext and exposes the DbSet properties that represent collections of the specified entities in the context.

options.UseMySql(connectionString,ServerVersion.AutoDetect(connectionString) configures Entity Framework to create and connect to a MySQL database.

UseSnakeCaseNamingConvention(): This will automatically make all your table and column names have snake_case naming.

namespace WebApi.Helpers;

using Microsoft.EntityFrameworkCore;
using WebApi.Entities;

public class DataContext : DbContext
{
    protected readonly IConfiguration Configuration;

    public DataContext(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        // connect to mysql with connection string from app settings
        var connectionString = Configuration.GetConnectionString("ApiDatabase");
        options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)).
        UseSnakeCaseNamingConvention();
    }

    public DbSet<User> Users { get; set; }
}


Global Error Handler Middleware

Path: /Helpers/ErrorHandlerMiddleware.cs

Using the global error handler, we can extract all the exception handling logic into a single centralized place. It's configured as middleware in the Program.cs file.

namespace WebApi.Helpers;

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;

public class ErrorHandlerMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;

    public ErrorHandlerMiddleware(RequestDelegate next, ILogger<ErrorHandlerMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception error)
        {
            var response = context.Response;
            response.ContentType = "application/json";

            switch (error)
            {
                case AppException e:
                    // custom application error
                    response.StatusCode = (int)HttpStatusCode.BadRequest;
                    break;
                case KeyNotFoundException e:
                    // not found error
                    response.StatusCode = (int)HttpStatusCode.NotFound;
                    break;
                default:
                    // unhandled error
                    _logger.LogError(error, error.Message);
                    response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    break;
            }

            var result = JsonSerializer.Serialize(new { message = error?.Message });
            await response.WriteAsync(result);
        }
    }
}


Interface User Service

Path: /Services/IUserService.cs

The user service is responsible for all database interaction and core business logic related to user CRUD operations.

namespace WebApi.Services;

using WebApi.Entities;
using WebApi.Models.Users;

public interface IUserService
{
    IEnumerable<User> GetAll();
    User GetById(int id);
    void Create(CreateRequest model);
    void Update(int id, UpdateRequest model);
    void Delete(int id);
}


User Service Implementation

Path: /Services/UserService.cs

The UserService.cs is a concrete user service class that implements the interface. 

using AutoMapper;
using WebApi.Entities;
using WebApi.Helpers;
using WebApi.Models.Users;

namespace WebApi.Services
{
    public class UserService : IUserService
    {
        private DataContext _context;
        private readonly IMapper _mapper;

        public UserService(
            DataContext context,
            IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        public IEnumerable<User> GetAll()
        {
            return _context.Users;
        }

        public User GetById(int id)
        {
            return getUser(id);
        }

        public void Create(CreateRequest model)
        {
            // validate
            if (_context.Users.Any(x => x.Email == model.Email))
                throw new AppException("User with the email '" + model.Email + "' already exists");

            // map model to new user object
            var user = _mapper.Map<User>(model);

            // save user
            _context.Users.Add(user);
            _context.SaveChanges();
        }

        public void Update(int id, UpdateRequest model)
        {
            var user = getUser(id);

            // validate
            if (model.Email != user.Email && _context.Users.Any(x => x.Email == model.Email))
                throw new AppException("User with the email '" + model.Email + "' already exists");

            // copy model to user and save
            _mapper.Map(model, user);
            _context.Users.Update(user);
            _context.SaveChanges();
        }

        public void Delete(int id)
        {
            var user = getUser(id);
            _context.Users.Remove(user);
            _context.SaveChanges();
        }

        // helper methods

        private User getUser(int id)
        {
            var user = _context.Users.Find(id);
            if (user == null) throw new KeyNotFoundException("User not found");
            return user;
        }
    }
}


CreateRequest.cs

Path: /Models/Users/CreateRequest.cs

namespace WebApi.Models.Users;

using System.ComponentModel.DataAnnotations;
using WebApi.Entities;

public class CreateRequest
{

    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }

}


UpdateRequest.cs

Path: /Models/Users/UpdateRequest.cs

namespace WebApi.Models.Users;

using System.ComponentModel.DataAnnotations;
using WebApi.Entities;

public class UpdateRequest
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [EmailAddress]
    public string Email { get; set; }


    private string replaceEmptyWithNull(string value)
    {
        return string.IsNullOrEmpty(value) ? null : value;
    }
}


Users Controller

Path: /Controllers/UsersController.cs

The controller defines and handles all routes / endpoints for the api that relate to users, this includes standard CRUD operations for retrieving, updating, creating and deleting users.

namespace WebApi.Controllers;

using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using WebApi.Models.Users;
using WebApi.Services;

[ApiController]
[Route("api/v1/[controller]")]
public class UsersController : ControllerBase
{
    private IUserService _userService;
    private IMapper _mapper;

    public UsersController(
        IUserService userService,
        IMapper mapper)
    {
        _userService = userService;
        _mapper = mapper;
    }

    [HttpGet]
    public IActionResult GetAll()
    {
        var users = _userService.GetAll();
        return Ok(users);
    }

    [HttpGet("{id}")]
    public IActionResult GetById(int id)
    {
        var user = _userService.GetById(id);
        return Ok(user);
    }

    [HttpPost]
    public IActionResult Create(CreateRequest model)
    {
        _userService.Create(model);
        return Ok(new { message = "User created" });
    }

    [HttpPut("{id}")]
    public IActionResult Update(int id, UpdateRequest model)
    {
        _userService.Update(id, model);
        return Ok(new { message = "User updated" });
    }

    [HttpDelete("{id}")]
    public IActionResult Delete(int id)
    {
        _userService.Delete(id);
        return Ok(new { message = "User deleted" });
    }
}


.NET 6 Program

Path: /Program.cs

Program.cs is the entry point of our app, where we configure the Web host. The program class configures the application infrastructure like Web host, logging, Dependency injection container, IIS integration, etc.

using System.Text.Json.Serialization;
using WebApi.Helpers;
using WebApi.Services;

var builder = WebApplication.CreateBuilder(args);

// add services to DI container
{
    var services = builder.Services;
    var env = builder.Environment;
 
    services.AddDbContext<DataContext>();
    services.AddCors();
    services.AddControllers().AddJsonOptions(x =>
    {
        // serialize enums as strings in api responses (e.g. Role)
        x.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());

        // ignore omitted parameters on models to enable optional params (e.g. User update)
        x.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    });
    services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

    // configure DI for application services
    services.AddScoped<IUserService, UserService>();
}

var app = builder.Build();

// configure HTTP request pipeline
{
    // global cors policy
    app.UseCors(x => x
        .AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader());

    // global error handler
    app.UseMiddleware<ErrorHandlerMiddleware>();

    app.MapControllers();
}

app.Run("http://localhost:9080");


.NET App Settings JSON

Path: /appsettings.json

The appsettings.json file is an application configuration file used to store configuration settings such as database connections strings, any application scope global variables, etc.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "ApiDatabase": "server=localhost:3306; database=testdb; user=knfuser; password=root"
  }
}


WebApi.csproj

Path: /WebApi.csproj

The csproj (C# project) is an MSBuild based file that contains target framework and NuGet package dependency information for the application.

The EFCore.NamingConventions plugin to automatically set all your table and column names to snake_case instead.

The Pomelo.EntityFrameworkCore.MySql is the Entity Framework Core (EF Core) provider for MySQL, MariaDB, Amazon Aurora, Azure Database for MySQL and other MySQL-compatible databases. It is build on top of MySqlConnector.

<Project Sdk="Microsoft.NET.Sdk.Web">
    <PropertyGroup>
        <TargetFramework>net6.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
    </PropertyGroup>
    <ItemGroup>
        <PackageReference Include="AutoMapper" Version="11.0.1" />
        <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="11.0.0" />
        <PackageReference Include="EFCore.NamingConventions" Version="7.0.2" />
        <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="7.0.0" />
    </ItemGroup>
</Project>


Run the application and verify REST APIs

You can start the api by running dotnet run from the command line in the project root folder (where the WebApi.csproj file is located), you should see the message Now listening on: http://localhost:9080.


OR


You can also start the application in debug mode in Visual Studio by opening the project root folder in Visual Studio and pressing F5 or by selecting Debug -> Start Debugging from the top menu, running in debug mode.


Add User:


Update User by ID:


Fetch all Users:


Get User by ID:


Delete User by ID:


PART 2 - UI development using Vue.js 3

Frontend Project Directory


package.json

Path: /package.json

The package.json is a JSON file that is added in the root directory of your project. It contains human-readable metadata about the project as well as functional metadata like the package version number and a list of dependencies required by the application.

{
  "name": "vue-3-crud-application",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "axios": "^0.21.1",
    "bootstrap": "^4.6.0",
    "core-js": "^3.6.5",
    "jquery": "^3.6.0",
    "popper.js": "^1.16.1",
    "vue": "^3.0.0",
    "vue-router": "^4.0.6"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^5.0.8",
    "@vue/cli-plugin-eslint": "^5.0.8",
    "@vue/cli-service": "^5.0.8",
    "@vue/compiler-sfc": "^3.0.0",
    "babel-eslint": "^10.1.0",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^7.0.0"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/vue3-essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "babel-eslint"
    },
    "rules": {}
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ]
}


Components

Vue Components are one of the important features of VueJS that creates custom elements, which can be reused in HTML.

User.vue

Path: /components/User.vue
<template>
  <div>
    <h3>User</h3>
    <div class="container">
      <form @submit="validateAndSubmit">
        <div v-if="errors.length">
          <div
            class="alert alert-danger"
            v-bind:key="index"
            v-for="(error, index) in errors"
          >
            {{ error }}
          </div>
        </div>
        <fieldset class="form-group">
          <label>First Name</label>
          <input type="text" class="form-control" v-model="firstName" />
        </fieldset>
        <fieldset class="form-group">
          <label>Last Name</label>
          <input type="text" class="form-control" v-model="lastName" />
        </fieldset>
        <fieldset class="form-group">
          <label>Email Id</label>
          <input type="text" class="form-control" v-model="email" />
        </fieldset>
        <button class="btn btn-success" type="submit">Save</button>
      </form>
    </div>
  </div>
</template>
<script>
import UserDataService from "../service/UserDataService";

export default {
  name: "User",
  data() {
    return {
      firstName: "",
      lastName: "",
      email: "",
      errors: [],
    };
  },
  computed: {
    id() {
      return this.$route.params.id;
    },
  },
  methods: {
    refreshUserDetails() {
      UserDataService.retrieveUser(this.id).then((res) => {
        this.firstName = res.data.firstName;
        this.lastName = res.data.lastName;
        this.email = res.data.email;
      });
    },
    validateAndSubmit(e) {
      e.preventDefault();
      this.errors = [];
      if (!this.firstName) {
        this.errors.push("Enter valid values");
      } else if (this.firstName.length < 5) {
        this.errors.push("Enter atleast 5 characters in First Name");
      }
      if (!this.lastName) {
        this.errors.push("Enter valid values");
      } else if (this.lastName.length < 5) {
        this.errors.push("Enter atleast 5 characters in Last Name");
      }
      if (this.errors.length === 0) {
        if (this.id == -1) {
          UserDataService.createUser({
            firstName: this.firstName,
            lastName: this.lastName,
            email: this.email,
          }).then(() => {
            this.$router.push("/");
          }, err => this.errors.push(err.response.data.errors));
        } else {
          UserDataService.updateUser(this.id, {
            id: this.id,
            firstName: this.firstName,
            lastName: this.lastName,
            email: this.email,
          }).then(() => {
            this.$router.push("/");
          }, err => this.errors.push(err.response.data.errors));
        }
      }
    },
  },
  created() {
    this.refreshUserDetails();
  },
};
</script>


Users.vue

Path: /components/Users.vue
<template>
    <div class="container">
      <h3>All Users</h3>
      <div v-if="message" class="alert alert-success">{{ this.message }}</div>
      <div class="container">
        <table class="table">
          <thead>
            <tr>
             
              <th>First Name</th>
              <th>Last Name</th>
              <th>Email Id</th>
              <th>Update</th>
              <th>Delete</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in users" v-bind:key="user.id">
           
              <td>{{ user.firstName }}</td>
              <td>{{ user.lastName }}</td>
              <td>{{ user.email }}</td>
              <td>
              <button class="btn btn-warning" v-on:click="updateUser(user.id)">
                  Update
                </button>
              </td>
              <td>
               <button class="btn btn-danger" v-on:click="deleteUser(user.id)">
                  Delete
                </button>
              </td>
            </tr>
          </tbody>
        </table>
        <div class="row">
          <button class="btn btn-success" v-on:click="addUser()">Add</button>
        </div>
      </div>
    </div>
  </template>
  <script>
  import UserDataService from "../service/UserDataService";
 
  export default {
    name: "Users",
    data() {
      return {
        users: [],
        message: "",
      };
    },
    methods: {
      refreshUsers() {
        UserDataService.retrieveAllUsers().then((res) => {
          this.users = res.data;
        });
      },
      addUser() {
        this.$router.push(`/user/-1`);
      },
      updateUser(id) {
        this.$router.push(`/user/${id}`);
      },
      deleteUser(id) {
        UserDataService.deleteUser(id).then(() => {
          this.refreshUsers();
        });
      },
    },
    created() {
      this.refreshUsers();
    },
  };
  </script>


UserDataService.js

Path: /service/UserDataService.js
import axios from 'axios'

const USER_API_URL = 'http://localhost:9080/api/v1'

class UserDataService {

    retrieveAllUsers() {
        return axios.get(`${USER_API_URL}/users`);
    }

    retrieveUser(id) {
        return axios.get(`${USER_API_URL}/users/${id}`);
    }

    deleteUser(id) {
        return axios.delete(`${USER_API_URL}/users/${id}`);
    }

    updateUser(id, user) {
        return axios.put(`${USER_API_URL}/users/${id}`, user);
    }
    createUser(user) {
        return axios.post(`${USER_API_URL}/users`, user);
    }
  }
export default new UserDataService()


App.vue

Path: /App.vue
<template>
  <div class="container">
    <div class="navbar-header">
      <a class="navbar-brand" href="#"
        >.Net 6 + MySQL + Vue.js 3 CRUD Application</a
      ><br /><br />
    </div>
    <router-view />
  </div>
</template>

<script>
export default {
  name: "app",
};
</script>


router.js

Path: /router.js
import { createWebHistory, createRouter } from "vue-router";

const routes =  [
    {
        path: "/",
        name: "Users",
        component: () => import("./components/Users"),
    },
    {
        path: "/user/:id",
        name: "User",
        component: () => import("./components/User"),
    },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;


main.js

Path: /main.js
import { createApp } from 'vue'
import App from './App.vue'
import 'bootstrap'
import 'bootstrap/dist/css/bootstrap.min.css'
import router from './router'

createApp(App).use(router).mount('#app')


Local Setup and Run the application

Download or clone the source code from GitHub to the local machine - Click here!



Backend


You can start the api by running dotnet run from the command line in the project root folder (where the WebApi.csproj file is located), you should see the message Now listening on: http://localhost:9080.


OR


You can also start the application in debug mode in Visual Studio by opening the project root folder in Visual Studio and pressing F5 or by selecting Debug -> Start Debugging from the top menu, running in debug mode.



Frontend


npm install


npm run serve -- --port 8081

From the browser call the endpoint http://localhost:8081

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete