ASP. NET Core Chinese Document Chapter 2 Guide (4.4) add Model, core4.4

Source: Internet
Author: User

ASP. NET Core Chinese Document Chapter 2 Guide (4.4) add Model, core4.4

Original article: Adding a model
By Rick Anderson
Translation: Lyrics)
Proofreading: Xu dengyang (Seay), Meng Shuai Yang (shuyuan), Yao ayong (Mr. Yao), and Xia shenbin

In this section, you will add some classes to manage movie data in the database. These classes will becomeMIn the VC application,MOdel section.

You will use the database access technology Named Entity Framework Core in. NET Framework to define and use these data model classes. Entity Framework Core (usually calledEFCore) has a special feature calledCode FirstDevelopment mode. Write the code first, and then use the code to create a database table. Code First allows you to create data model objects by writing some simple classes (also called POCO classes, "plain-old CLR objects."), and then create databases based on your classes. If you need to create a database first, you can still follow this tutorial to learn about MVC and EF application development.

Create a new project using personal account Identity Authentication

In the current version of ASP. NET Core MVC in Visual Studio, you can generate a model through the base frame only when creating a new project using personal account authentication. We hope to fix this issue in the next tool update. You need to create a new project with the same name until the problem is fixed. Because the project has the same name, you need to create it in other folders.

In Visual studioStart Page), ClickNew Project)


Alternatively, you can use the menu to create a new project. ClickFile> New> Project).


CompleteNew Project)Dialog Box:

  • In the left pane, clickWeb
  • In the middle pane, clickASP. NET Core Web Application (. NET Core)
  • Change the location to the different directories of the previous project you created. Otherwise, you will encounter an error.
  • Name the project as "MvcMovie" (it is very important to name the project as "MvcMovie". When you copy the code, the namespace will match)
  • ClickOK)



caveat
 In this tutorial, you must set the authentication to individual user accounts (Individual User Accounts) so that the scaffolding engine can work normally. In order for the tutorial to proceed smoothly, the personal user account authentication method must be selected here.


 
In the New ASP.NET Core Web Application-MvcMovie dialog box:

Click Web Application
Click the Change Authentication button and change the authentication to Individual User Accounts and click OK
Follow the change-title-link-reference-label instructions and you can click the MvcMovie link to call the Movie Controller. In this tutorial, we will generate a Movie Controller from the base frame.

Add Data Model Class
In Solution Explorer, right-click the Models folder> Add> Class. Name the class name Movie and add the following attributes:

using System;

namespace MvcMovie.Models
{
    public class Movie
    {
        public int ID {get; set;} // manually highlight
        public string Title {get; set;}
        public DateTime ReleaseDate {get; set;}
        public string Genre {get; set;}
        public decimal Price {get; set;}
    }
}
In addition to the attributes you used to construct the movie, you also need an ID field as the database primary key. Build the project. If you do not generate this application, you will encounter errors in the next section. We finally added a Model to this MVC application.

Generate a controller through the base frame (Controller)
In Solution Explorer, right-click on the Controllers folder> Add> Controller

In the Add Scaffold dialog box, click MVC Controller with views, using Entity Framework> Add.

Complete the Add Controller dialog box

Model class: Movie (MvcMovie.Models)
Data context class (Data context class): ApplicationDbContext (MvcMovie.Models)
Views: Keep the default options
Controller name (Controller name): Keep the default MoviesController
Click Add
The things created by the Visual Studio scaffolding engine are as follows:

A movie controller (Controller) (Controllers / MoviesController.cs)
Create, Delete, Details, Edit, and Index Razor view files (Views / Movies)
Visual Studio automatically creates CRUD (create, read, update, and delete) Action methods and views for you (automatically creating CRUD Action methods and View views is called scaffolding). Soon you will have a fully functional web application that allows you to create, view, edit, and delete movie entries.

Run this application and click on the Mvc Movie link. You will encounter the following error:

We will follow these instructions to prepare the database for the Movie application.

Update the database
caveat
 You must stop IIS Express before updating the database.


 
Stop IIS Express:
Right-click the IIS Express system tray icon in the notification area
Click Exit or Stop Site
In addition, you can exit and restart Visual Studio

Open a command prompt in the project folder (MvcMovie / src / MvcMovie). Follow the instructions below to open the project folder in a quick way

Open a file in the root directory of the project (in this example, use Startup.cs).
Right-click Startup.cs> Open Containing Folder.

Shift + right-click on a folder> Open command window here
Run cd: return the path to the project folder

Run the following command in the command prompt:

  dotnet ef migrations add Initial
  dotnet ef database update
note
 If IIS-Express is running, you will encounter the error CS2012: Cannot open 'MvcMovie / bin / Debug / netcoreapp1.0 / MvcMovie.dll' for writing-'The process cannot access the file' MvcMovie / bin / Debug / netcoreapp1.0 / MvcMovie.dll 'because it is being used by another process.'


 
dotnet ef command
dotnet (.NET Core) is a cross-platform implementation of .NET. You can learn about it here.
dotnet ef migrations add Initial Run the Entity Framework .NET Core CLI migration command and create an initial migration. The parameter "Initial" can be any value, but this is usually used as the first (initial) database migration. This operation creates a * Data / Migrations / _Initial.cs * file, which contains the migration commands to add (or delete) Movie tables to the database.
dotnet ef database update dotnet ef database update Update the database with the migration we just created.
have a test
note
 If your browser cannot connect to the Movie application, you may need to wait for IIS Express to load it. It sometimes takes 30 seconds to build the application and be ready to respond to requests.


 
Run the application and click on the Mvc Movie link
Click the Create New link and create a movie
note
 You may not be able to enter a decimal point or comma in the Price field. In order to implement comma (",") to represent the decimal point in a non-English environment, and jQuery validation in a non-US English date format, you must take steps to internationalize your application. See additional resources for more information. Now just enter the complete number, such as 10.


 
note
 In some regions you need to specify the date format. See the highlighted code below.


 
Click Create to submit the form to the server and save the movie data to the database. Then redirect to the / Movies URL and you can see the newly created movie in the list.

using System;
using System.ComponentModel.DataAnnotations; // Manual highlight

namespace MvcMovie.Models
{
    public class Movie
    {
        public int ID {get; set;}
        public string Title {get; set;}
        [DisplayFormat (DataFormatString = "{0: yyyy-MM-dd}", ApplyFormatInEditMode = true)] // Manual highlight
        public DateTime ReleaseDate {get; set;}
        public string Genre {get; set;}
        public decimal Price {get; set;}
    }
}
Create a few more movie entries. Try Edit, Details, Delete links to perform various functions.

Check the generated code
Open the Controllers / MoviesController.cs file and check the generated Index method. The part of MoviesController that contains the Index method is as follows:

public class MoviesController: Controller
{
    private readonly ApplicationDbContext _context;

    public MoviesController (ApplicationDbContext context)
    {
        _context = context;
    }

    // GET: Movies
    public async Task <IActionResult> Index ()
    {
        return View (await _context.Movie.ToListAsync ());
    }
The constructor uses dependency injection to inject the database context into the controller. The data context is used in the Controller to execute the CRUD method.

A request to MoviesController returns all entries from the Movies table, and then passes the data to the Index view (View).

Strongly typed models with @model keyword
In the previous tutorial, you saw how the Controller passes data to a view through the ViewData dictionary. The ViewData dictionary is a dynamically typed object that provides a convenient way of late binding to pass information to the view.

MVC also provides the ability to pass strongly typed data to the view. This strongly typed approach can provide you with better code compile-time checks and a richer sense of intelligence in Visual Studio (VS). The scaffolding mechanism in VS uses this approach when creating methods (actions) and views (views) for the MoviesController class (ie, passing a strongly typed model).

Check the Details method generated in the Controllers / MoviesController.cs file:

// GET: Movies / Details / 5
public async Task <IActionResult> Details (int? id)
{
    if (id == null)
    {
        return NotFound ();
    }

    var movie = await _context.Movie.SingleOrDefaultAsync (m => m.ID == id);
    if (movie == null)
    {
        return NotFound ();
    }

    return View (movie);
}
The id parameter is generally passed as routing data, for example http: // localhost: 1234 / movies / details / 1 will:

Controller is set to movies (corresponding to the first URL segment)
Action is set to details (corresponding to the second URL segment)
id is set to 1 (corresponding to the last URL segment)
You can also pass id through the query string (Query String) as follows:

http: // localhost: 1234 / movies / details? id = 1

If the movie is found, the Movie Model (Model)

The instance will be passed to the Details view (View).

  return View (movie);
Check the contents of the Views / Movies / Details.cshtml file:

@model MvcMovie.Models.Movie <!-Manual highlight->

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

<h2> Details </ h2>

<div>
    <h4> Movie </ h4>
    <hr />
    <dl class = "dl-horizontal">
        <dt>
            @ Html.DisplayNameFor (model => model.Genre)
        </ dt>
        <dd>
            @ Html.DisplayFor (model => model.Genre)
        </ dd>
        <dt>
            @ Html.DisplayNameFor (model => model.Price)
        </ dt>
        <dd>
            @ Html.DisplayFor (model => model.Price)
        </ dd>
        <dt>
            @ Html.DisplayNameFor (model => model.ReleaseDate)
        </ dt>
        <dd>
            @ Html.DisplayFor (model => model.ReleaseDate)
        </ dd>
        <dt>
            @ Html.DisplayNameFor (model => model.Title)
        </ dt>
        <dd>
            @ Html.DisplayFor (model => model.Title)
        </ dd>
    </ dl>
</ div>
<div>
    <a asp-action="Edit" asp-route-id="@Model.ID"> Edit </a> |
    <a asp-action="Index"> Back to List </a>
</ div>
By adding a @model statement at the top of the View (View Template) file, you can specify the object type that the View expects. When you create this MoviesController, Visual Studio automatically adds the part after the @model statement at the top of Details.cshtml.

  @model MvcMovie.Models.Movie
The @model directive allows you to access this strongly typed movie Model object passed from the Controller to the View. For example, in the Details.cshtml view, the code uses a strongly-typed Model object to pass all movie fields to the DisplayNameFor and DisplayFor HTML Helper classes (HTML Helper). The Create and Edit methods and View also pass a Movie model object.

Check the Index method in the Index.cshtml view (View) and MoviesController. Notice how the code creates a List object when calling the View method. This code passes the Movies list from the Index Action method to the view:

public async Task <IActionResult> Index ()
{
    return View (await _context.Movie.ToListAsync ());
}
When you create this MoviesController, Visual Studio automatically adds the following @model statement at the top of Index.cshtml:

@model IEnumerable <MvcMovie.Models.Movie>
The @model directive allows you to access the movie list, a strongly typed Model object passed from the Controller to the View. For example, in the Index.cshtml view, the code traverses the movie list, a strongly typed Model object, through the foreach statement.

@model IEnumerable <MvcMovie.Models.Movie> <!-Manual highlighting->

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

<h2> Index </ h2>
<p>
    <a asp-action="Create"> Create New </a>
</ p>

<table class = "table">
    <thead>
        <tr>
            <th>
                @ Html.DisplayNameFor (model => model.Genre)
            </ th>
            <th>
                @ Html.DisplayNameFor (model => model.Price)
            </ th>
            <th>
                @ Html.DisplayNameFor (model => model.ReleaseDate)
            </ th>
            <th>
                @ Html.DisplayNameFor (model => model.Title)
            </ th>
            <th> </ th>
        </ tr>
    </ thead>
    <tbody>
@foreach (var item in Model) {<!-Manual highlight->
        <tr>
            <td>
                @ Html.DisplayFor (modelItem => item.Genre) <!-Manual highlighting->
            </ td>
            <td>
                @ Html.DisplayFor (modelItem => item.Price) <!-Manual highlighting->
            </ td>
            <td>
                @ Html.DisplayFor (modelItem => item.ReleaseDate) <!-Manual highlight->
            </ td>
            <td>
                @ Html.DisplayFor (modelItem => item.Title) <!-Manual highlight->
            </ td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.ID"> Edit </a> | <!-Manual highlighting->
                <a asp-action="Details" asp-route-id="@item.ID"> Details </a> | <!-Manual highlighting->
                <a asp-action="Delete" asp-route-id="@item.ID"> Delete </a> <!-Manual highlight->
            </ td>
        </ tr>
}
    </ tbody>
</ table>
Because Model objects are strongly typed (as IEnumerable <Movie> objects), the type of each item in the loop is typed as Movie. Among other benefits, this means that you will get compile-time checking of the code and full intellisense support in the code editor:

Now you have a database and pages for displaying, editing, updating, and deleting data. In the next tutorial, we will learn to use the database.

Additional resources
Tag Helpers
Internationalization and localization
revise history

Back to Contents
The

Reference page:

http://www.yuanjiaocheng.net/ASPNET-CORE/core-razor-taghelpers.html

http://www.yuanjiaocheng.net/ASPNET-CORE/core-edit-form.html

http://www.yuanjiaocheng.net/ASPNET-CORE/core-identity.html

http://www.yuanjiaocheng.net/ASPNET-CORE/core-authorize-attribute.html

http://www.yuanjiaocheng.net/ASPNET-CORE/core-identity-configuration.html

it learning materials


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.