MVC基础篇(MVC basics)

MAR 14, 2023

一、Create Project(VS Code)

  • Init project

Terminal -> New Terminal

cd .\Documents\
dotnet new mvc -o veic_web --framework net6.0
  • Set workspace dir

File -> Add Folder to Workspace

设置缺省首页(Home Set Default)

  • Program.cs
app.UseStaticFiles();

变更为:

app.UseDefaultFiles();
app.UseStaticFiles();
  • Html
    新建wwwroot/index.html,See附录1.

Run

Run -> Start Debugging

运行效果:home page

二、Data

namespace:

namespace veic_web.Models;

Table

You can choose between MySQL or MSSQL.

Ms SQL Server See附录2

1. Add package

Enter the project folder (the directory where the “.csproj” file is located).

cd veic_web

update NuGet:

dotnet nuget add source --name nuget.org https://api.nuget.org/v3/index.json

EF Core

  • Release
CLI> dotnet add package Microsoft.EntityFrameworkCore --version 6.0.14
  • Preview
CLI> dotnet add package Microsoft.EntityFrameworkCore --prerelease

MySQL

  • Pomelo
CLI> dotnet add package Pomelo.EntityFrameworkCore.MySql --version 6.0.2
  • Oracle
CLI> dotnet add package MySql.EntityFrameworkCore --version 6.0.7

MS Sql

CLI> dotnet add package Microsoft.EntityFrameworkCore.Relational --version 6.0.14
  • Release
CLI> dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 6.0.14
  • Preview
CLI> dotnet add package Microsoft.EntityFrameworkCore.SqlServer --prerelease

2. Entity Framework

entity class

Product.cs:

using System.ComponentModel.DataAnnotations;

namespace veic_web.Models;

public class Product
{
    [Key]
    public int Id { get; set; }
    public int Param_id { get; set; }
    public int Statu_id { get; set; }
    public int Lang_id { get; set; }
    public int Img_id { get; set; }
    public string? Name { get; set; }
    public string? Description { get; set; }
}

DB Context

ApplicationDbContext.cs

引用:

using Microsoft.EntityFrameworkCore;

实现:

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {

    }
}

Entity支持

    public DbSet<Product> Products { get; set; } = default!;

3. Usage EF

首先添加数据库context,然后添加Repository。

addDbContext

  • MySQL
    Pomelo:
 MySql - Pomelo
builder.Services.AddDbContext<ApplicationDbContext>(options =>
                        options.UseMySql(builder.Configuration["Data:VeicWeb:ConnectionString"],
                            new MySqlServerVersion(new Version(5, 7, 38)))
                .EnableSensitiveDataLogging());

Oracle:

 MySql - Oracle
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseMySQL(builder.Configuration["Data:VeicWeb:ConnectionString"]));
  • LocalDB
 MS Sql
builder.Services.AddDbContext<ApplicationDbContext>(options =>
                        options.UseSqlServer(builder.Configuration["Data:mslocaldb:ConnectionString"])
                .EnableSensitiveDataLogging());

DB Connection String

appsettings.json

  • MySQL
"Data": {
    "VeicWeb": {
        "ConnectionString": "server=127.0.0.1; user id=DBAdmin; password=xbfirst; database=carnumber; pooling=false; Convert Zero Datetime=True;"
    }
}
    "Data":{
       "mslocaldb": {
          "ConnectionString": "Server=(LocalDB)\\MSSQLLocalDB;Database=carnumber;MultipleActiveResultSets=true"
        }
    }

addTransient

use瞬时模式, 添加Repository:

builder.Services.AddTransient<IProductRepository, EFProductRepository>();

Repository类

引用:

using System.Linq;

接口:

public interface IProductRepository
{
    IQueryable<Product> Products { get; }
}

实现:

public class EFProductRepository : IProductRepository
{
    private readonly ApplicationDbContext context;

    public EFProductRepository(ApplicationDbContext ctx)
    {
        this.context = ctx;
    }

    public IQueryable<Product> Products => context.Products;
}

三、View-Controller

Views/Home/Index.cshtml: 由

    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>

替换为:

    <p>Learn about <a href="/home/list">查看产品列表</a></p>

Views/Home/ProductList.cshtml:

@model IEnumerable<Product>
@foreach (var p in Model!)
{
    <div>
        <h3>@p.Name</h3>
        @p.Description
    </div>
}

Controller

HomeController.cs

声明product repository:

    private readonly IProductRepository _repository;

DI:

    public HomeController(ILogger<HomeController> logger, IProductRepository repo)
    {
        _logger = logger;
        _repository = repo;
    }

引用实例:添加新方法

    public IActionResult List(int countPage = 1)
    {
        var repo = _repository.Products.Where(lang => lang.Lang_id.Equals(langId)).OrderBy(p => p.Id)
            .Skip((countPage - 1) * pageSize)
            .Take(pageSize);
        return View("ProductList", repo);
    }

增加分页: 声明公共成员变量

    public int pageSize = 3;
    public int langId = 4075;

project code:

附录

1

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>公司类网站ASP.NET 6.0</title>
    </head>
<body>
    <div>
        <marquee>欢迎来到ASP.NET世界</marquee>
    </div>

    <div>
        <p align="center"><a href="javascript:void(0)" onClick="callPage('home')" >中文</a>&nbsp;&nbsp;&nbsp;&nbsp;
        <a href="javascript:void(0)" onClick="callPage('home/privacy')" >ENGLISH</a></p>
    </div>

    <script type="text/javascript">
        callPage = function(linkAddr) {;
            window.location.href=window.location + linkAddr;
            // window.open(window.location + linkAddr);
        };
    </script>

</body>

</html>

2

down navicat for sqlserver; later install Microsoft SQL Server 2012 Native Client(sqlncli.msi - amd64)
Host:

(localdb)\v11.0

create db:

CREATE DATABASE carnumber;

create table:

USE [carnumber]
GO

/****** Object:  Table [dbo].[products]    Script Date: 2021/8/14 8:47:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[products](
    [id] [int] NOT NULL,
    [param_id] [int] NOT NULL,
    [statu_id] [int] NOT NULL,
    [lang_id] [int] NOT NULL,
    [img_id] [int] NOT NULL,
    [name] [varchar](80) NULL,
    [description] [text] NULL,
 CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

LocalDB

About vs2013 installation files:
All feature packages are in “packages”;

  • sqllocaldb_amd64
    64-bit installation package of ms sql2012 localdb
  • sqlncli_amd64
    64-bit installation package of Microsoft SQL Server 2012 Native Client

see instances:

sqllocaldb i

Nullable

Variable

声明中增加:

?

使用中增加:

!

Program

增加注释:

#nullable disable

Reference

Logo

更多推荐