Monday, October 31, 2022
HomeWordPress DevelopmentCreate a fundamental CRUD App with .NET MVC & EF

Create a fundamental CRUD App with .NET MVC & EF


I created a fundamental CRUD App to get began with .NET MVC and Entity Framework.

The app is a Film Ranker Desk that shows Films and Film Particulars ordered by rating.

Image description

You possibly can add new entries to the desk, edit present entries and delete them.

Add Movie Records

Edit Movie Records

Delete Movie Records

To get the complete code you should clone the repository:

This is learn how to do it

The repository in query is as follows:

A CRUD Model MVC App utilizing Entity Framework. Lets you View, Add, Edit, Delete and Rank motion pictures by Rating

This venture is a perfect foundational instance to study MVC with Entity Framework.

At its core, it’s merely a desk displaying information of Films and their rating (in descending order) in line with a rating – assigned by the consumer, which is outlined between 0 and 100. The consumer can visualize the information ranked by Rating, they’ll add new information, edit present information and delete them as properly. Notification messages present on the prime proper each time an operation has been profitable.

Though the app is easy, there are numerous options of MVC functions at play.

The listing of options is lengthy, listed below are a few of them:

Options

On the Entrance Finish:

  • Creation of Fashions contained in the view with the Create motion so as to add information.
  • Displaying of Mannequin information inside the Views
  • Use of GetBootstrap.com’s navigation bar and icons
  • Implementation of Bootswatch Theme
  • …

There within the venture description one can find a prolonged listing of options.

At its most elementary, I wanted to create a connection string in appsettings.json

// connection string in appsettings.json

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

Enter fullscreen mode

Exit fullscreen mode

Then a database context.

// Software DbContext Class in Knowledge Folder ApplicationDbContext.cs

utilizing Microsoft.EntityFrameworkCore;
utilizing MVCMovieRanker.Fashions;

namespace MVCMovieRanker.Knowledge
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> choices) : base(choices)
        {

        }

        public DbSet<Film> Films { get; set; }
    }

}

Enter fullscreen mode

Exit fullscreen mode

After which move the connection object with particulars in Program.cs

// connection arrange in program.cs

var builder = WebApplication.CreateBuilder(args);

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

;
var app = builder.Construct();

Enter fullscreen mode

Exit fullscreen mode

Then I wanted to do EF migrations to create the tables within the database primarily based on the mannequin. After which add some dummy information to visualise.

The mannequin I created is as follows:

namespace MVCMovieRanker.Fashions
{
    [Table("Movies")]
    public class Film
    {
        [Key]
        public int MovieId { get; set; }
        [Required]
        [MaxLength(100)]
        [Column("MovieName")]
        public string Identify { get; set; }
        public string? Style { 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 Rating { get; set; }
    }
}

Enter fullscreen mode

Exit fullscreen mode

Then I created a Film Controller (full code with Create, Edit and Delete Actions within the repo), right here exhibiting the implementation of the Index View solely which ranks the films each time it hundreds.

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

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

        public IActionResult Index()
        {
            IEnumerable<Film> objMovieList = _db.Films;
            var objMovieListSorted = from objMovie in objMovieList
                                 orderby objMovie.Rating descending
                                 choose objMovie;

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

Exit fullscreen mode

And for every Motion a View or a redirect to view. This is what the Film Index Motion seems to be like:

// View

@mannequin IEnumerable<Film>

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

<partial title="_Notification" />


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

<desk class="desk tabled-bordered table-striped" model="width: 100%">
    <thead>
        <tr>
            <th width="20%">
                Film Identify
            </th>
            <th>
                Style
            </th>
            <th>
                Launch Date
            </th>
            <th>
                Studio
            </th>
            <th>
                Rating
           </th>
           <th>

           </th>
        </tr>
    </thead>
    <tbody>
        @foreach(var obj in Mannequin)
        {
            <tr>
                <td width="20%">
                    @obj.Identify
                </td>
                <td width="15%">
                    @obj.Style
                </td>
                <td width="15%">
                    @obj.ReleaseDate.ToShortDateString()
                </td>
                <td width="15%">
                    @obj.Studio
                </td>
                <td width="15%">
                    @obj.Rating
                </td>
                <td>
                    <div class="w-50 btn-group d-inline" function="group">
                            <a asp-controller="Film" 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" function="group">
                            <a asp-controller="Film" 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>
</desk>
</div>
Enter fullscreen mode

Exit fullscreen mode

The easiest way to work by way of this venture is to comply with by way of with a listing of duties in thoughts.

To notice, on the backend, you need to begin with the creation of the mannequin, returning to it so as to add information annotations as wanted so you may carry out information visualization and validation.

After creating the mannequin, you need to obtain related packages like Entity Framework Core, Entity Framework SQL Server, and Entity Framework Instruments.

It’s best to then proceed with connecting the Mannequin to the database through entity framework:
1) Outline your connection string in appsettings.json
2) Create an ApplicationDbContext class
3) Add scripts to the builder in Program.cs to make sure connection to the database
4) Use Entity Framework’s add-migration and update-database instructions to create the Mannequin code first into the database
5) Create dummy information in your database to visualise and take a look at CRUD operations

Aside from having an Index motion (for an index view) the place you need to carry out a LINQ question to order information, you need to have actions for the opposite views Create, Edit and Delete (each GET and POST variations).

On these actions you will carry out some server-side validations with ModelState.IsValid, with the assistance of Knowledge Annotations within the Mannequin, in addition to Add, Replace and Take away information.

Right here you will additionally fetch the mannequin’s information by id, in addition to move mannequin objects to views.

You will discover the code for all of those steps within the MovieController.

The Views (one view per motion roughly) will show mannequin information or assist the consumer populate it with intensive use of Tag Helpers.

On the frontend you will additionally resort to Bootstrap and Bootswatch for css and js recordsdata which may be refrenced within the _Layout grasp web page or in a partial view.

Partial views will also be used to offer frontend validations with jquery validation scripts.

You will additionally add javascript scripts for managing alerts with Tostr.js utilizing TempData.

Holding all of this in thoughts, now you can bounce into the code and discover the complete implementation.

Take pleasure in!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments