ASP.NET Core 3 高级编程(第8版) 学习笔记 03

本篇介绍原书的第 18 章,为 19 章 Restful Service 编写基础代码。本章实现了如下内容:
1)使用 Entity Framework Core 操作 Sql Server 数据库
2)Entity Framework Core 数据库迁移和使用种子数据的方法
3)使用中间件 (middleware) 来配置请求管道 (request pipeline)

Nuget 包

为了运行本章代码,需要下面的三个包:

Microsoft.EntityFrameworkCore.SqlServer --version 3.1.1
Microsoft.EntityFrameworkCore.Design --version 3.1.1
Microsoft.EntityFrameworkore.Tool --version 3.1.1

数据模型

创建 Products, Category 和 Suppliers 三个实体模型:

namespace WebApp.Models
{public class Category{public long CategoryId { get; set; }public string Name { get; set; }public IEnumerable<Product> Products { get; set; }}
}
namespace WebApp.Models
{public class Supplier{public long SupplierId { get; set; }public string Name { get; set; }public string City { get; set; }public IEnumerable<Product> Products { get; set; }}
}
namespace WebApp.Models
{public class Product{public long ProductId { get; set; }public string Name { get; set; }public decimal Price { get; set; }  public long CategoryId { get; set; }public Category Category { get; set; }public long SupplierId { get; set; }public Supplier Supplier { get; set; }  }
}

创建 DbContext 类

using Microsoft.EntityFrameworkCore;namespace WebApp.Models
{public class DataContext : DbContext{public DataContext(DbContextOptions<DataContext> opts) : base(opts) { }public DbSet<Product> Products { get; set; }public DbSet<Category> Categories { get; set; }public DbSet<Supplier> Suppliers { get; set; }}
}

种子数据

using Microsoft.EntityFrameworkCore;
using System.Linq;namespace WebApp.Models
{public class SeedData{public static void SeedDatabase(DataContext context){context.Database.Migrate();// 只有在空的时候才填充数据if (context.Products.Count() == 0 && context.Suppliers.Count() == 0 && context.Categories.Count() == 0) {// 供应商var s1 = new Supplier{Name = "Splash Dudes",City = "San Jose"};var s2 = new Supplier{Name = "Soccer Town",City = "Chicago"};var s3 = new Supplier { Name = "Chess Co",City = "New York"};// Categoryvar c1 = new Category { Name = "Watersports" };var c2 = new Category { Name = "Soccer" };var c3 = new Category { Name = "Chess" };context.Products.AddRange(new Product { Name = "Kayak", Price = 275, Category = c1, Supplier = s1} ,new Product { Name = "LifeJacket", Price = 48.95m, Category = c1, Supplier = s1} , new Product { Name = "Soccer ball", Price = 19.50m, Category= c2, Supplier = s2} ,new Product { Name = "Corner Flags", Price = 34.95m, Category= c2, Supplier = s2} ,new Product { Name = "Stadium", Price = 79500, Category= c2, Supplier = s2} ,new Product { Name = "Thinking Cap", Price = 16, Category= c3, Supplier = s3} ,new Product { Name = "Unsteady Chair", Price = 29.95m, Category= c3, Supplier = s3} ,new Product { Name = "Human Chess Board", Price = 75, Category= c3, Supplier = s3} ,new Product { Name = "Bling-Bling King", Price = 1200, Category= c3, Supplier = s3} );context.SaveChanges();}}}
}

数据库连接字符串

使用 Sql Server LocalDB,将数据库连接字符串写在 appsettings.json 文件。

{"Logging": {"LogLevel": {"Default": "Information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "Information","Microsoft.EntityFrameworkCore": "Information"}},"AllowedHosts": "*","ConnectionStrings" : {"ProductConnection" : "Server=(localdb)\\MSSQLLocalDB;Database=Products;MultipleActiveResultSets=True"}
}

配置 Entity Framework Core

在 Startup.cs 的 Configure() 方法中进行配置:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApp.Models;namespace WebApp
{public class Startup{public Startup(IConfiguration config){Configuration = config;}public IConfiguration Configuration { get; set; }// This method gets called by the runtime. Use this method to add services to the container.// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940public void ConfigureServices(IServiceCollection services){services.AddDbContext<DataContext>(opts =>{opts.UseSqlServer(Configuration["ConnectionStrings:ProductConnection"]);//opts.EnableSensitiveDataLogging(true);});}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext context){         if (env.IsDevelopment()) {app.UseDeveloperExceptionPage();}app.UseRouting();app.UseEndpoints(endpoints =>{endpoints.MapGet("/", async context =>{await context.Response.WriteAsync("Hello World!");});});SeedData.SeedDatabase(context);}}
}

注意:Configure() 方法在默认代码的基础上增加了 DbContext 参数,目的是启动的时候自动运行向数据库添加种子数据。

数据库迁移

打开 Package Manager Console (Tools > Nuget Package Manager > Package Manager Console),运行下面两个命令:

Add-migration initDatabae
update-database

Add-migration 命令将创建迁移脚本
update-database 将未提交的变化提交到数据库。

运行之后,使用 SQL Server Object Explorer (View > SQL Server Object Explore)可以看到,数据库和表都已经正确创建。

使用中间件配置请求管道

希望实现的效果是 Http Get 请求 /test 能返回三张表的数据条数。

创建 TestMiddleware 中间件:

using Microsoft.AspNetCore.Http;
using System.Linq;
using System.Threading.Tasks;
using WebApp.Models;namespace WebApp
{public class TestMiddleware{private RequestDelegate nextDelegate;public TestMiddleware(RequestDelegate nextDelegate){this.nextDelegate = nextDelegate;}public async Task Invoke(HttpContext context, DataContext dataContext){if (context.Request.Path == "/test") {await context.Response.WriteAsync($"There are {dataContext.Products.Count()} prodcts.\n");await context.Response.WriteAsync($"There are {dataContext.Categories.Count()} categories.\n");await context.Response.WriteAsync($"There are {dataContext.Suppliers.Count()} suppliers.\n");} else {await nextDelegate(context);}}}
}

在 Startup.cs 文件中配置中间件。

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApp.Models;namespace WebApp
{public class Startup{public Startup(IConfiguration config){Configuration = config;}public IConfiguration Configuration { get; set; }// This method gets called by the runtime. Use this method to add services to the container.// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940public void ConfigureServices(IServiceCollection services){services.AddDbContext<DataContext>(opts =>{opts.UseSqlServer(Configuration["ConnectionStrings:ProductConnection"]);//opts.EnableSensitiveDataLogging(true);});}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext context){         if (env.IsDevelopment()) {app.UseDeveloperExceptionPage();}app.UseRouting();app.UseMiddleware<TestMiddleware>();app.UseEndpoints(endpoints =>{endpoints.MapGet("/", async context =>{await context.Response.WriteAsync("Hello World!");});});SeedData.SeedDatabase(context);}}
}

源码

pro asp.net core 3 notes: 《ASP.NET Core 3高级编程(第8版)》学习笔记

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/3561.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Babylon.js 读取GLB模型元数据

如果你熟悉将 3D 资源导出到游戏引擎的过程&#xff0c;那么无疑也会熟悉 3D 资源的 PBR 和 GLB 导出过程。 这是我们之前概述的内容&#xff0c;也是我们交互式工作的所有资产准备的基石。 然而&#xff0c;从传统的管道意义上来说&#xff0c;能够用元数据标记网格有很多逻辑…

通配符HTTPS安全证书

众多类型的SSL证书&#xff0c;要说适用或者说省钱肯定是通配符了&#xff0c;因为谁都想一本SSL证书包括了整条域名&#xff0c;而且也不用一条一条单独管理。 通配符HTTPS安全证书&#xff0c;其实就是通配符SSL证书&#xff0c;SSL证书主流CA的参数都一样&#xff0c;通配符…

【MHA】MySQL高可用MHA介绍8-常见错误以及解决

目录 MHA Node 未安装在 MySQL 服务器上 找不到主服务器的二进制日志 没有对二进制/中继日志授予读权限 使用多主复制&#xff08;不受支持&#xff09; 这些日志是 MHA Manager 在执行故障检测和故障切换过程中遇到的一些问题的记录。让我为您解释一下每个错误消息的含义&…

武汉星起航:亚马逊助力中国卖家扬帆出海,迎来跨境电商新机遇

2015年&#xff0c;亚马逊全球开店业务正式踏入中国这片充满活力和潜力的市场&#xff0c;此举不仅为中国卖家提供了前所未有的跨境电商新机遇&#xff0c;更为其发展出口业务、拓展全球市场、打造国际品牌铺设了一条坚实的道路。亚马逊作为国际版的电商购物平台&#xff0c;其…

Hadoop-Hive-Spark-离线环境搭建

一、版本描述 apache-hive-2.3.9-bin.tar.gz hadoop-2.7.0.tar.gz spark-2.4.0-bin-hadoop2.7.tgz 下载链接&#xff1a; https://archive.apache.org/dist/spark/spark-2.4.0/spark-2.4.0-bin-hadoop2.7.tgz https://archive.apache.org/dist/hadoop/common/hadoop-2.7.…

js中onchange的使用场景及如何使用

使用场景&#xff1a; onchange 事件常用于表单元素&#xff08;如 input、select、textarea 等&#xff09;的值发生改变时触发相应的操作。可以用于实时监测用户输入的内容&#xff0c;进行验证或实时更新相关内容。 示例代码&#xff1a; <!DOCTYPE html> <html…

vscode 创建代码模版

在vscode中快捷创建代码模版 1.在VSCode中&#xff0c;按下Ctrl Shift P&#xff08;Windows/Linux&#xff09;或Cmd Shift P&#xff08;Mac&#xff09;打开命令面板。 2.然后输入"Preferences: Configure User Snippets"并选择该选项。打开一个json文件用户…

vue3 update:modelValue 用法

在Vue 3中&#xff0c;update:modelValue是v-model指令的默认事件&#xff0c;用于在组件内部通知父组件更新绑定的值。这种命名约定是固定的&#xff0c;当你在组件上使用v-model而没有指定参数时。然而&#xff0c;Vue 3也提供了灵活性&#xff0c;允许开发者自定义绑定的属性…

IDEA中配置使用maven和配置maven的中央仓库

1 以汉化后的IDEA为例配置maven 打开idea选择文件 选择 设置 点击>构建.执行.部署 点击>构建工具 点击>Maven 其中Maven主路径 就是我们maven下载解压后的路径 可以通过边上的三个点选择你解压后的绝对路径&#xff0c;也可以直接把解压后的绝对路劲复制过来 以下…

回归预测 | Matlab实现SSA-ESN基于麻雀搜索算法优化回声状态网络的多输入单输出回归预测

回归预测 | Matlab实现SSA-ESN基于麻雀搜索算法优化回声状态网络的多输入单输出回归预测 目录 回归预测 | Matlab实现SSA-ESN基于麻雀搜索算法优化回声状态网络的多输入单输出回归预测预测效果基本介绍程序设计参考资料 预测效果 基本介绍 1.Matlab实现SSA-ESN基于麻雀搜索算法…

物联网:从电信物联开发平台AIoT获取物联设备上报数据示例

设备接入到电信AIoT物联平台后&#xff0c;可以在平台上查询到设备上报的数据。 下面就以接入的NBIOT物联远传水表为例。 在产品中选择指定设备&#xff0c;在数据查看中可以看到此设备上报的数据。 示例中这组数据是base64位加密的&#xff0c;获取后还需要转换解密。 而我…

实现异步的8种方式

一、前言 在编程中&#xff0c;有时候我们需要处理一些费时的操作&#xff0c;比如网络请求、文件读写、数据库操作等等&#xff0c;这些操作会阻塞线程&#xff0c;等待结果返回。为了避免阻塞线程、提高程序的并发处理能力&#xff0c;我们常常采用异步编程。 异步编程是一种…

2024 IDM最新破解版及软件介绍

*IDM&#xff1a;信息时代的高效管理工具** 在快节奏的现代社会中&#xff0c;随着信息的爆炸式增长&#xff0c;如何高效、有序地管理信息成为每个人都需要面对的挑战。IDM&#xff0c;作为一种信息管理工具&#xff0c;正在逐渐受到人们的青睐。 IDM&#xff0c;全称Inform…

Linux--进程控制(1)

文章衔接&#xff1a; Linux--环境变量-CSDN博客 Linux--地址空间-CSDN博客 目录 1.进程创建 2.进程的终止 2.1想明白&#xff1a;终止是在做什么&#xff1f; 2.2进程终止的三种情况 2.3 进程如何终止 3.进程等待 &#xff08;wait/waitpid&#xff09; 1.进程创建 在li…

C++内存分布 new和delete介绍

目录 C/C内存分布 栈区 堆区 静态区 常量区 C new和delete 分配空间形式对比 new delete与malloc free的区别 可不可以串着使用new和free呢 C/C内存分布 C的内存分布&#xff0c;大体上分为栈区 堆区 静态区 常量区 栈区 栈区是用于存储函数调用时的局部变量 函…

MySQL——运维

日志 错误日志 错误日志是 MySQL 中最重要的日志之一&#xff0c;它记录了当 mysqld 启动和停止时&#xff0c;以及服务器在运行过程中发生任何严重错误时的相关信息。当数据库出现任何故障导致无法正常使用时&#xff0c;建议首先查看此日志。 查看日志位置&#xff1a; sho…

Eigen::svd和 np.linalg.svd的不同之处

目录 pythonc结论参考 SVD奇异值分解与PCA主成分分析 SVD动画图解–Wiki Eigen Svd 和 np.linalg.svd都可以用于SVD计算&#xff0c;但两者却存在细微的差别。 python import numpy as np datanp.array([[0.99337785, 0.08483806, 0.07747866, -92.91055059],[-0.07889607,…

【Qt常用控件】—— 多元素控件

目录 1.1 List Widget 1.2 Table Widget 1.3 Tree Widget 1.4 小结 Qt 中提供的多元素控件有: QListWidget QListView QTableWidget QTableView QTreeWidget QTreeView xxWidget 和 xxView 之间的区别 以 QTableWidget 和 QTableView 为例&#xff1a; QTableView 是基于…

自动驾驶---OpenSpace之Hybrid A*规划算法

1 背景 笔者在上周发布的博客《自动驾驶---低速场景之记忆泊车》中,大体介绍了记忆泊车中的整体方案,其中详细阐述了planning模块的内容,全局规划及局部规划(会车)等内容,包括使用的算法,但是没有深入详细地展开讲述OpenSpace规划算法,因此在本篇博客中,详细讲解该部分…

03-JAVA设计模式-备忘录模式

备忘录模式 什么是备忘录模式 Java中的备忘录模式&#xff08;Memento Pattern&#xff09;是一种行为型设计模式&#xff0c;它允许在不破坏封装性的前提下捕获一个对象的内部状态&#xff0c;并在该对象之外保存这个状态&#xff0c;以便以后可以将对象恢复到原先保存的状态…