ASP.NET Core MVC models

In ASP.NET Core MVC, the model represents the data required for a request. For example, an HTTP GET request for http://www.example.com/products/details/3 might mean that the browser is asking for the details of product number 3.

The controller would need to use the ID value 3 to retrieve the record for that product and pass it to a view that can then turn the model into HTML for display in the browser.

In the following example, we will create an Entity Framework Core data model to directly access data in the Northwind database.

Tip

Good Practice

Use a data repository (typically implemented as a service) to manage your data instead of accessing it directly in an ASP.NET Core MVC web application.

Create Entity models for Northwind

Follow the instructions in Chapter 8, Working with Databases Using the Entity Framework Core, to create the Northwind database:

  • On Windows, create it in the (local)mssqllocaldb server. If you completed the earlier chapters, then you have already done this.
  • On macOS, create the Northwind.db file in the inDebug etcoreapp1.1 folder by copying the NorthwindSQLite.sql file into that folder, and then enter the following command in Terminal:
      sqlite3 Northwind.db < NorthwindSQLite.sql

In both Visual Studio 2017 and Visual Studio Code, add three class files to the Models folder named Northwind.cs, Category.cs, and Product.cs.

Northwind.cs should look like this:

    using Microsoft.EntityFrameworkCore; 
 
    namespace Packt.CS7 
    { 
      public class Northwind : DbContext 
      { 
        public DbSet<Category> Categories { get; set; } 
        public DbSet<Product> Products { get; set; } 
        public Northwind(DbContextOptions options) : base(options) 
           {} 
      } 
    } 

Note

We will set the database connection string in the ASP.NET Core startup so it does not need to be done in the Northwind class, but the class derived from DbContext must have a constructor with a DbContextOptions parameter.

Category.cs should look like this:

    using System.ComponentModel.DataAnnotations; 
 
    namespace Packt.CS7 
    { 
      public class Category 
      { 
        public int CategoryID { get; set; } 
        [Required] 
        [StringLength(15)] 
        public string CategoryName { get; set; } 
        public string Description { get; set; } 
      } 
    } 

Supplier.cs should look like this:

    using System.ComponentModel.DataAnnotations; 
    using System.ComponentModel.DataAnnotations.Schema; 
 
    namespace Packt.CS7 
    { 
      [Table("Suppliers")]
      public class Supplier 
      { 
        public int SupplierID { get; set; } 
        [Required] 
        [StringLength(15)] 
        public string CompanyName { get; set; } 
      } 
    } 

Product.cs should look like this:

    using System.ComponentModel.DataAnnotations; 
 
    namespace Packt.CS7 
    { 
      public class Product 
      { 
        public int ProductID { get; set; } 
        [Required] 
        [StringLength(40)] 
        public string ProductName { get; set; } 
        public int? SupplierID { get; set; } 
        public Supplier Supplier { get; set; } 
        public int? CategoryID { get; set; } 
        public Category Category { get; set; } 
        [StringLength(20)] 
        public string QuantityPerUnit { get; set; } 
        public decimal? UnitPrice { get; set; } 
        public short? UnitsInStock { get; set; } 
        public short? UnitsOnOrder { get; set; } 
        public short? ReorderLevel { get; set; } 
        public bool Discontinued { get; set; } 
      } 
    } 

Tip

Good Practice

Create a separate class library project for your entity models. This allows easier sharing between servers and clients.

Configure Entity Framework Core as a service

Services, such as the Entity Framework Core, that are needed by MVC controllers must be registered as a service during startup.

Open the Startup.cs file.

Add the following statement to the ConfigureServices method.

For Windows with SQL Server LocalDb:

    services.AddDbContext<Packt.CS7.Northwind>(options => 
      options.UseSqlServer(Configuration 
      .GetConnectionString("NorthwindConnection"))); 

For macOS with SQLite:

    services.AddDbContext<Packt.CS7.Northwind>(options => 
      options.UseSqlite(Configuration 
      .GetConnectionString("NorthwindConnection"))); 

Open the appsettings.json file and add a connection string.

For Windows with SQL Server LocalDb:

    "NorthwindConnection":
    "Server=(localdb)\mssqllocaldb;Database=Northwind;Trusted_Connect
    ion=True;MultipleActiveResultSets=true" 

For macOS with SQLite:

    "NorthwindConnection": "Data Source=Northwind.db" 

Create view models for requests

Imagine that when a user comes to our website, we want to show them a list of products and a count of the number of visitors we have had this month. All the data that we want to show in response to a request is the MVC model, sometimes called a view model, because it is a model that is passed to a view.

Add a class to the Models folder and name it HomeIndexViewModel.

Modify the class definition to make it look like this:

    using System.Collections.Generic; 
 
    namespace Packt.CS7 
    { 
      public class HomeIndexViewModel 
      { 
        public int VisitorCount; 
        public ICollection<Product> Products { get; set; } 
      } 
    } 

Fetch the model in the controller

Open the HomeController class.

Import the Packt.CS7 namespace.

Add a field to store a reference to a Northwind instance and initialize it in a constructor:

    private Northwind db; 
 
    public HomeController(Northwind injectedContext) 
    { 
      db = injectedContext; 
    } 

Modify the contents of the Index action method to make it look like this:

    var model = new HomeIndexViewModel 
    { 
      VisitorCount = (new Random()).Next(1, 1001), 
      Products = db.Products.ToArray() 
    }; 
    return View(model); // pass model to view 

Note

We will simulate a visitor count using the Random class to generate a number between 1 and 1000.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.216.254