Build a Basic CRUD App with .NET MVC and EF

I built a basic CRUD app to get started with .NET MVC and Entity Framework.

The app is a movie ranker table that displays movie and movie details based on score.

You can add new entries to the table, edit existing entries, and delete them.

add movie record

edit movie record

delete movie record

You need to clone the repository to get the complete code:

here’s how to do it

The reserves in question are as follows:

A CRUD style MVC app using Entity Framework. Allows you to watch, add, edit, delete and rank movies by score

This project is a perfect foundational example for learning MVC with Entity Framework.

At its core, it’s just a table that displays a record of movies and their ranking (in descending order) according to a score – specified by the user, which is defined between 0 and 100. User can visualize records ranked by score, they can add new records, edit existing records and delete them too. Whenever an operation is successful, notification messages appear in the top right.

Although the app is simple, many features of MVC applications are in play.

The list of features is long, here are some of them:

features

On front end:

  • Creating the model inside the view with the Create action to add the record.
  • Displaying model data within views
  • Using GetBootstrap.com’s Navigation Bar and Icons
  • Bootswatch theme implementation
  • ,

There in the project description you will find a long list of features.

At its most basic, I like appsettings.json. need to create a connection string in

// connection string in appsettings.json

"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=MovieRanker;Trusted_Connection=True;"
  }

enter fullscreen mode

exit fullscreen mode

Then a database reference.

// Application DbContext Class in Data Folder ApplicationDbContext.cs

using Microsoft.EntityFrameworkCore;
using MVCMovieRanker.Models;

namespace MVCMovieRanker.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {

        }

        public DbSet<Movie> Movies { get; set; }
    }

}

enter fullscreen mode

exit fullscreen mode

and then Program.cs. pass connection object with details in

// connection set up in program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
// Register ApplicationDbContext
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(
// Register the connection string in appsettings.json
    builder.Configuration.GetConnectionString("DefaultConnection")
    ));

;
var app = builder.Build();

enter fullscreen mode

exit fullscreen mode

Then I needed to do EF Migrations to create tables in the database based on the model. And then add some dummy data to visualize.

The model I have created is as follows:

namespace MVCMovieRanker.Models
{
    [Table("Movies")]
    public class Movie
    {
        [Key]
        public int MovieId { get; set; }
        [Required]
        [MaxLength(100)]
        [Column("MovieName")]
        public string Name { get; set; }
        public string? Genre { get; set; }
        [DataType(DataType.Date)]
        [DisplayName("Release Date")]
        //[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
        public DateTime ReleaseDate { get; set; }
        public string? Studio { get; set; }
        [Required]
        public int Score { get; set; }
    }
}

enter fullscreen mode

exit fullscreen mode

Then I created a movie controller (complete code with create, edit and delete actions in the repo), here just showing the implementation of the index view which ranks the movies every time it is loaded.

// Controller
  public class MovieController : Controller
    {
        private readonly ApplicationDbContext _db;

        public MovieController(ApplicationDbContext db)
        {
            _db = db;
        }

        public IActionResult Index()
        {
            IEnumerable<Movie> objMovieList = _db.Movies;
            var objMovieListSorted = from objMovie in objMovieList
                                 orderby objMovie.Score descending
                                 select objMovie;

            //return View(objMovieList);
            return View(objMovieListSorted);
        }
...
enter fullscreen mode

exit fullscreen mode

And a view or redirect to watch for each action. The movie index action looks like this:

// View

@model IEnumerable<Movie>

@{
    ViewData["Title"] = "Index";
}

<partial name="_Notification" />


<div class="container p-3">
    <div class="row pt-4">
        <div class="col-6">
            <h2 class="text-primary">Movie List</h2>
        </div>
        <div class="col-6 text-end">
            <a asp-controller="Movie" asp-action="Create" class="btn btn-primary">
                <i class="bi bi-plus-circle"></i> &nbsp; Add New Movie 
            </a>
        </div>
    </div>
    <br /><br />

<table class="table tabled-bordered table-striped" style="width: 100%">
    <thead>
        <tr>
            <th width="20%">
                Movie Name
            </th>
            <th>
                Genre
            </th>
            <th>
                Release Date
            </th>
            <th>
                Studio
            </th>
            <th>
                Score
           </th>
           <th>

           </th>
        </tr>
    </thead>
    <tbody>
        @foreach(var obj in Model)
        {
            <tr>
                <td width="20%">
                    @obj.Name
                </td>
                <td width="15%">
                    @obj.Genre
                </td>
                <td width="15%">
                    @obj.ReleaseDate.ToShortDateString()
                </td>
                <td width="15%">
                    @obj.Studio
                </td>
                <td width="15%">
                    @obj.Score
                </td>
                <td>
                    <div class="w-50 btn-group d-inline" role="group">
                            <a asp-controller="Movie" asp-action="Edit" asp-route-id="@obj.MovieId"
                            class="btn btn-primary mx-2"> 
                                <i class="bi bi-pencil-square"></i>Edit</a>
                    </div>
                    <div class="w-50 btn-group d-inline" role="group">
                            <a asp-controller="Movie" asp-action="Delete" asp-route-id="@obj.MovieId"
                            class="btn btn-danger mx-2">
                                <i class="bi bi-trash-fill"></i>Delete </a>
                    </div>
                </td>
            </tr>
        }
    </tbody>
</table>
</div>
enter fullscreen mode

exit fullscreen mode

The best way to work through this project is by jotting down a list of tasks to follow.

Note, on the backend, you should start with building the model, returning to it to add data annotations as needed so you can perform data visualization and validation.

After creating the model, you should download the relevant packages like Entity Framework Core, Entity Framework SQL Server and Entity Framework Tools.

You should then proceed to connect the model to the database via entity framework:
1) Define your connection string in appsettings.json
2) Create an ApplicationDbContext class
3) Add the script to the builder in Program.cs to ensure the connection to the database
4) Use Entity Framework’s Add-Migration and Update-Database commands to create the model code first in the database
5) Create dummy data in your database to visualize and test CRUD operations

In addition to having an index action (for the index view), where you must perform a LINQ query to order the records, you must also have actions for the other views create, edit and delete (both GET and POST versions).

On these actions you will do some server-side validation with the help of data annotations in the model with ModelState.IsValid, as well as add, update and remove records.

Here you will also fetch the model’s data by id, as well as pass the model object to the view.

You can find the code for all these steps in MovieController.

The view (roughly one view per action) will display model data or help the user to populate it with extensive use of tag helpers.

On the frontend you’ll also resort to bootstrap and bootstrap for the css and js files, which can be referenced in the _Layout master page or partial view.

Partial views can also be used with jQuery validation scripts to provide frontend validation.

You would also add a JavaScript script to manage alerts with Tostr.js using TempData.

With all this in mind, you can now jump into the code and explore the full implementation.

enjoy!

image

Leave a Comment