My Blog List

Friday, September 25, 2020

ASP.NET Core 3.1 MVC | EntityFrameworkCore | Visual Studio 2019 for Mac | CRUD Operations | MySQL

Today we will create an asp.net core MVC application using EntityFramework and MySQL Database with Visual Studio 2019 for Mac.

This is a simple CRUD operation for an Employe using ASP.NET Core 3.1 and EntityFrameworkCore


Prerequisites:
  1. Visual Studio 2019 IDE for Mac
  2. Make sure you are running the latest .Net core 3.1
  3. Install the latest DOTNET and EF CLI using this command: dotnet tool install --global dotnet ef
  4. MySQL database should be installed on your Mac

Getting Started:

         Open the Visual Studio 2019 for Mac and Create a New Project as below

    
     Please select the .Net Core 3.1  as below


        I created a new project with the Name, "DotNetCore" and below is the Solution structure which
        is created by VS2019.



        Let's install the few mandatory nuget packages as below

                        1. Microsoft.EntityFrameworkCore
                        2. Microsoft.EntityFrameworkCore.Design
                        3. Microsoft.EntityFrameworkCore.Tools
                        4. MySql.Data
                        5. MySql.Data.EntityFrameworkCore

        Now let's add a New Class name "DotNetCoreDbContext" under the Models folder by 
right-clicking
        and select Add New Class.


        Now let's write the code for this class.
        We have to inherit our class from the DbContext class by using Microsoft.EntityFrameworkCore
        
using System;
using Microsoft.EntityFrameworkCore;
namespace DotNetCore.Models
{
public class DotNetCoreDbContext : DbContext
{
public DotNetCoreDbContext(DbContextOptions<DotNetCoreDbContext> options): base(options)
{
}
}
}
        Now let's add a New Class name "Employee" under the Models folder.
        
        
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace DotNetCore.Models
{
public class Employee
{
[Key]
public int EmployeeID { get; set; }
[Required(ErrorMessage ="Please enter the full name!")]
[DisplayName("Full Name")]
public string FullName { get; set; }
[Required(ErrorMessage = "Please enter the employee code!")]
[DisplayName("Employee Code")]
public string EmpCode { get; set; }
[Required(ErrorMessage = "Please enter the position!")]
[DisplayName("Position")]
public string Position { get; set; }
[Required(ErrorMessage = "Please enter the location!")]
[DisplayName("Location")]
public string Location { get; set; }
}
}
view raw Employee.cs hosted with ❤ by GitHub
        Now add our class into DotNetCoreDbContext as below
        
using System;
using Microsoft.EntityFrameworkCore;
namespace DotNetCore.Models
{
public class DotNetCoreDbContext : DbContext
{
public DotNetCoreDbContext(DbContextOptions<DotNetCoreDbContext> options): base(options)
{
}
public DbSet<Employee> Employees { get; set; }
}
}
        Now we need to write code for ConnectionStrings in appsettings.json file
        and modify the Startup.cs file as below
        
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=dotnetcore;Uid=root;Pwd=root@123;"
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DotNetCore.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
namespace DotNetCore
{
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)
{
services.AddControllersWithViews();
services.AddDbContext<DotNetCoreDbContext>(options => options.UseMySQL(Configuration.GetConnectionString("DefaultConnection")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Employee}/{action=Index}/{id?}");
});
}
}
}
view raw Startup.cs hosted with ❤ by GitHub
        Next step to add the Migration to create the Database in MySql

        Run below command w.r.t your project folder path on Terminal
        
        To Add-Migration:
        dotnet ef migrations add InitialCreate

        To Update-Database
        dotnet ef database update

        To Remove-Migration:
        dotnet ef migrations remove

        After adding the Migration, we can see our database has been created into the MySql database

        We can see our created database dotnetcore including the Employees table.


           Now let's add the controller name "EmployeeController" using Scaffolding as below
        
            

        We will use the same action for Create and Edit an Employee.
        Let's write the code for AddOrEdit action into EmployeeController
        
// GET: Employee/AddOrEdit
public IActionResult AddOrEdit(int Id=0)
{
if(Id==0)
return View(new Employee());
else
return View(_context.Employees.Find(Id));
}
        Now let's add the view page for AddOrEdit action under the Views/Employee folder

        
@model DotNetCore.Models.Employee
@{
ViewData["Title"] = "Create";
}
<h4>Employee Form</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="AddOrEdit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="EmployeeID" />
<div class="form-group">
<label asp-for="FullName" class="control-label"></label>
<input asp-for="FullName" class="form-control" />
<span asp-validation-for="FullName" class="text-danger"></span>
</div>
<div class="row">
<div class="form-group col-md-6">
<label asp-for="EmpCode" class="control-label"></label>
<input asp-for="EmpCode" class="form-control" />
<span asp-validation-for="EmpCode" class="text-danger"></span>
</div>
<div class="form-group col-md-6">
<label asp-for="Position" class="control-label"></label>
<input asp-for="Position" class="form-control" />
<span asp-validation-for="Position" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Location" class="control-label"></label>
<input asp-for="Location" class="form-control" />
<span asp-validation-for="Location" class="text-danger"></span>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<input type="submit" value="Submit" class="btn btn-primary btn-block" />
</div>
<div class="form-group col-md-6">
<a asp-action="Index" class="btn btn-secondary btn-block"><i class="fa fa-table"></i> Back to List</a>
</div>
</div>
</form>
</div>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
        We have written the code to create and edit an employee, added the view page also.
        Now let's build our solution and run the application.
        Let's create 3-4 employees by entering the required fields as below

        Let's write some action methods to Index, Details, and Delete an employee as well

// GET: Employee
public async Task<IActionResult> Index()
{
return View(await _context.Employees.ToListAsync());
}
// GET: Employee/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var employee = await _context.Employees
.FirstOrDefaultAsync(m => m.EmployeeID == id);
if (employee == null)
{
return NotFound();
}
return View(employee);
}
// GET: Employee/Delete/5
public async Task<IActionResult> Delete(int? id)
{
var employee = await _context.Employees.FindAsync(id);
_context.Employees.Remove(employee);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
        Below are the screenshots for Index, Details, and Delete action methods

        https://localhost:5001/Employee/Index


        https://localhost:5001/Employee/Details/1



        Now let's delete the Harshit Kumar record... it will show an alert popup message as below


        Harshit Kumar record has been deleted from the database as we can see the below
    
        

           Below is the Employee table screenshot



        I hope it will help you :)
        
        Please comment if you face any issue regarding the same...

        You can download the source code from GitHub by click on the below link

Below is the video of my running application:




5 comments:

  1. Good to know information buddy..this really helps

    ReplyDelete
  2. Indeed a nice read worth sharing, thanks geek.

    ReplyDelete
  3. Getting the below error while doing migration please help anyone ?

    Method 'Create' in type 'MySql.Data.EntityFrameworkCore.Query.Internal.MySQLSqlTranslatingExpressionVisitorFactory' from assembly 'MySql.Data.EntityFrameworkCore, Version=8.0.22.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' does not have an implementation.

    ReplyDelete