Use ASP.NET MVC Code First + Demo

Tram Ho

1. Introduction

What is Entity Framework Code First ??

  • Simply put, “Code First” helps you to build structured data from model classes (or business / domain classes).
  • Entity Framework Code-First will help you do all the other steps, from creating databases, creating tables, querying data, and so on. If there is a change in class structure, Entity Framework Code-First can also help you to convert the corresponding database structure quickly and conveniently, especially without losing old data.

2. Demo of building book management application with Code First.

2.1. Prepare

  • Visual Studio 2012 -> 2019
  • SQL Server
  • Entity Framework -> Open Package Manager Console -> install-package entityframework
  • Here I will create a separate database for easy observation.

2.2. Proceed

Step 1: Create a database

  • I will create a database called BookManager with 2 tables linked together to get 2 tables data as well.

  • The Category table will contain information for the type of book.
  • Book table will contain the book’s information (title, image, creation date, blabla … )
  • The foreign key will be the CategoryID that links to the Category table to get the book category name.

The data of 2 tables will be the same as above

Step 2: Create project

  • I will create an MVC project called BookManager .

Step 3: Create Model

  • Right-click Model -> Add -> New item -> through the data, select ADO.NET .

  • Click on Code First

  • Enter Server Name and select the database name

  • Check all added tables -> Finish

Step 4: Create Controller

  • Right click on Controller folder -> Add -> controller -> MVC 5 Controller With views, using Entity Framework.

  • Select Model Class as the Model you want to create corresponding to the table in the database, I will create a table of book types.

  • Do the same with the Model book

  • After creating the controller, you will look at the Views that will have .cshtml files corresponding to adding, editing, deleting and displaying.

Step 5: Customize

  • You can edit the interface and display name in .cshtml files, the structure is still the same as .html file.

  • The site address will be structured as follows: localhost: {Port} / {Controller} / {Action}
  • You can customize the page switch in _Layout.cshtml

3. Summary

  • So I have completed the demo of creating an project using the first code. The article will have many errors, you can contribute more comments to make the following articles better. Good luck!!!

4. References

Share the news now

Source : Viblo