学习ASP.NET Core Blazor编程系列二——第一个Blazor应用程序(下)

 
 

学习ASP.NET Core Blazor编程系列三——实体这篇文章中我们创建了数据库上下文BookContex类,这个类就是用于处理数据库连接和将Book实体对象映射到数据库表(Book)记录。数据库上下文(BookContext)是在Program.cs文件的builder.Services.AddDbContextFactory方法中向依赖关系注入容器进行注册,具体代码如下:

builder.Services.AddDbContextFactory<BookContext>(opt =>
opt.UseSqlServer(ConfigHelper.Configuration["ConnectionStrings:BookContext"]));

为了进行本地开发,我们在appsettings.json 文件中配置数据库连接字符串,数据库连接配置如下:

  "ConnectionStrings": {
"BookContext": "Server=.;Database=LeaseBook;Trusted_Connection=True;
MultipleActiveResultSets=true"
}

将应用程序部署到测试或生产服务器时,可以修改Appsettings.json文件中上将配置,将数据库连接字符串设置为真正的SQL服务器。

学习ASP.NET Core Blazor编程系列四——迁移这篇文章中我们通过EF Core提供的迁移功能,创建了数据库表。

学习ASP.NET Core Blazor编程系列五——列表页面这篇文章我们创建了图书列表页面,不过由于数据库中没有数据,我们的图书列表页面上也是一片空白没有数据显示。

今天的这篇文章,我们将通过EF Core6提供的功能,向数据库表Book中添加初始数据。

 一、给数据库添加初始数据

在Visual Studio 2022 的解决方案资源管理器中,使用鼠标左键选中Models文件,然后点击鼠标右键,在弹出菜单中选择“添加--》类”,创建一个新的类文件,命名为SeedData。具体代码如下:

using Microsoft.EntityFrameworkCore;

namespace BlazorAppDemo.Models
{
public class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new BookContext(serviceProvider.
GetRequiredService<DbContextOptions<BookContext>>()))
{
// Look for any Books.
if (context.Book.Any())
{
return; // DB has been seeded
}
context.Book.AddRange(
new Book
{
Name = "Python编程 从入门到实践",
ReleaseDate = DateTime.Parse("2018-1-12"),
Author = "埃里克·马瑟斯",
Price = 75.99M,
StockQty=10,
Qty=0,
TotalPages=445,
Type=""
}, new Book
{
Name = "Java编程的逻辑",
ReleaseDate = DateTime.Parse("2018-1-13"),
Author = "马俊昌",
Price = 48.99M,
StockQty = 12,
Qty = 0,
TotalPages = 675,
Type = ""
},
new Book
{
Name = "统计思维:大数据时代瞬间洞察因果的关键技能",
ReleaseDate = DateTime.Parse("2017-12-23"),
Author = "西内启",
Price = 39.99M,
StockQty = 20,
Qty = 0,
TotalPages = 330,
Type = ""
}, new Book
{
Name = "微信营销",
ReleaseDate = DateTime.Parse("2018-01-05"),
Author = "徐林海",
Price = 33.99M,
StockQty = 30,
Qty = 0,
TotalPages = 266,
Type = ""
}
);
context.SaveChanges();
}
}
}
}

以下语句的作用是 如果数据库中有Book表,数据初始化类将返回,不添加任何数据。

           // Look for any Books.
if (context.Book.Any())
{
return; // DB has been seeded
}

 二、添加SeedData.initializer方法

1.在Visual Studio 2022 的解决方案资源管理器中打开Program.cs文件,然后找到Main方法,在这个方法体的最后面添加SeedData.Initialize()方法,代码如下:


using BlazorAppDemo.Data;
using BlazorAppDemo.Models;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
System.Console.WriteLine(ConfigHelper.Configuration["ConnectionStrings:BookContext"]);
builder.Services.AddDbContextFactory<BookContext>(opt =>
opt.UseSqlServer(ConfigHelper.Configuration["ConnectionStrings:BookContext"])); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts();
} //数据库数据初始化
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
Console.WriteLine("数据库开始初始化。");
var context = services.GetRequiredService<BookContext>();
// requires using Microsoft.EntityFrameworkCore;
context.Database.Migrate();
// Requires using BlazorAppDemo.Models;
SeedData.Initialize(services);
Console.WriteLine("数据库初始化结束。");
} catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "数据库数据初始化错误.");
} } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();

2.在Visual Studio 2022中的菜单上选择“生成-->开始调试”,或按F5键。运行BlazorAppDemo应用程序。如下图。将进行数据库初始化。

三、测试应用程序

1.在Visual Studio 2022中,打开“Pages\BookIndex.razor”文件,在此文件的顶部,输入@inject IDbContextFactory<BookContext> dbFactory,注入数据库上下文。

2.在@code中重写OnInitializedAsync方法 ,在组件呈现时,去查询数据库中的Book表中的数据,最终呈现在页面上。具体代码如下。

@page "/BookIndex"
@using BlazorAppDemo.Models
@using Microsoft.EntityFrameworkCore @inject IDbContextFactory<BookContext> dbFactory <PageTitle>图书列表</PageTitle> <h3>图书列表</h3> <table class="table-responsive" width="90%">
<tr><td>Name</td>
<td>Author</td>
<td>Price</td>
<td>ReleaseDate</td>
<td>StockQty</td>
<td>Qty</td>
</tr> @foreach (var item in books)
{
<tr>
<td>@item.Name</td>
<td>@item.Author</td>
<td>@item.Price</td>
<td>@item.ReleaseDate</td>
<td>@item.StockQty</td>
<td>@item.Qty</td>
</tr> } </table> @code { private static BookContext _context;
private List<Book> books = new List<Book>(); protected override async Task OnInitializedAsync()
{ _context = dbFactory.CreateDbContext();
books=_context.Book.ToList();
await base.OnInitializedAsync();
}
}

3. 在Visual Studio 2022中的菜单上选择“生成à开始调试”,或按F5键。运行BlazorAppDemo应用程序。使用鼠标右键点击浏览器中左边的菜单栏中的“图书列表”菜单,在浏览器中显示图书信息。如下图。

学习ASP.NET Core Blazor编程系列六——初始化数据的更多相关文章

  1. 学习ASP.NET Core Blazor编程系列六——新增图书(上)

    学习ASP.NET Core Blazor编程系列一--综述 学习ASP.NET Core Blazor编程系列二--第一个Blazor应用程序(上) 学习ASP.NET Core Blazor编程系 ...

  2. 学习ASP.NET Core Blazor编程系列八——数据校验

    学习ASP.NET Core Blazor编程系列一--综述 学习ASP.NET Core Blazor编程系列二--第一个Blazor应用程序(上) 学习ASP.NET Core Blazor编程系 ...

  3. 学习ASP.NET Core Blazor编程系列九——服务器端校验

    学习ASP.NET Core Blazor编程系列一--综述 学习ASP.NET Core Blazor编程系列二--第一个Blazor应用程序(上) 学习ASP.NET Core Blazor编程系 ...

  4. 学习ASP.NET Core Blazor编程系列十——路由(上)

    学习ASP.NET Core Blazor编程系列一--综述 学习ASP.NET Core Blazor编程系列二--第一个Blazor应用程序(上) 学习ASP.NET Core Blazor编程系 ...

  5. 学习ASP.NET Core Blazor编程系列二——第一个Blazor应用程序(完)

    学习ASP.NET Core Blazor编程系列一--综述 学习ASP.NET Core Blazor编程系列二--第一个Blazor应用程序(上) 学习ASP.NET Core Blazor编程系 ...

  6. 学习ASP.NET Core Blazor编程系列十——路由(中)

    学习ASP.NET Core Blazor编程系列一--综述 学习ASP.NET Core Blazor编程系列二--第一个Blazor应用程序(上) 学习ASP.NET Core Blazor编程系 ...

  7. 学习ASP.NET Core Blazor编程系列二——第一个Blazor应用程序(上)

    学习ASP.NET Core Blazor编程系列一--综述 一.概述 Blazor 是一个生成交互式客户端 Web UI 的框架: 使用 C# 代替 JavaScript 来创建信息丰富的交互式 U ...

  8. 学习ASP.NET Core Blazor编程系列二——第一个Blazor应用程序(中)

    学习ASP.NET Core Blazor编程系列一--综述 学习ASP.NET Core Blazor编程系列二--第一个Blazor应用程序(上) 四.创建一个Blazor应用程序 1. 第一种创 ...

  9. 学习ASP.NET Core Blazor编程系列二——第一个Blazor应用程序(下)

    学习ASP.NET Core Blazor编程系列一--综述 学习ASP.NET Core Blazor编程系列二--第一个Blazor应用程序(上) 学习ASP.NET Core Blazor编程系 ...

随机推荐

  1. react 吸顶实现

    今天获取到一个需求,其实就是吸顶的需求,页面下滑,某一块dom隐藏时发生吸顶现象.这种特效其实老生常谈了,但是在这次做的时候,突发奇想,能否将其做成一个 hook ,从而实现出传递ref即可使得 do ...

  2. 业务可视化-让你的流程图"Run"起来(4.实际业务场景测试)

    前言 首先,感谢大家对上一篇文章[业务可视化-让你的流程图"Run"起来(3.分支选择&跨语言分布式运行节点)]的支持. 下面我以实际业务场景为例,来介绍一下ladybug ...

  3. linux学习随笔

    date +%Y-%m-%d\ %H:%M:%S cal 10 2009 yum install bc //计算器 bc 安装thefuck yum install gcc gcc++ python ...

  4. 蔚来杯2022牛客暑期多校训练营5 ABCDFGHK

    比赛链接 A 题解 知识点:图论,dp. 暴力建图,连接所有点的双向通路,除了原点是单向的,并且把路径长度作为权值. 随后,从原点出发(\(f[0] = 0\),其他点负无穷,保证从原点出发),按照权 ...

  5. SpringBoot 如何集成 MyBatisPlus - SpringBoot 2.7.2实战基础

    SpringBoot 2.7.2 学习系列,本节通过实战内容讲解如何集成 MyBatisPlus 本文在前文的基础上集成 MyBatisPlus,并创建数据库表,实现一个实体简单的 CRUD 接口. ...

  6. linux常见命令(十二)

    sed/egrep将order.txt文件按行号展示出来,并删除第2,4行nl order.txt |sed '2,4d'将order.txt文件按行号展示出来,并删除第3行nl order.txt ...

  7. FPGA/Verilog 资源整理

    verilog学习教程(以Vivado为载体)https://vlab.ustc.edu.cn/guide/index.html 中科大的数电实验网站https://vlab.ustc.edu.cn/

  8. 长篇图解java反射机制及其应用场景

    一.什么是java反射? 在java的面向对象编程过程中,通常我们需要先知道一个Class类,然后new 类名()方式来获取该类的对象.也就是说我们需要在写代码的时候(编译期或者编译期之前)就知道我们 ...

  9. 记录第一次给开源项目提 PR

    本文是深入浅出 ahooks 源码系列文章的第八篇,该系列已整理成文档-地址.觉得还不错,给个 star 支持一下哈,Thanks. 本篇文章算是该系列的一个彩蛋篇,记录一下第一次给开源项目提 PR ...

  10. React报错之Parameter 'event' implicitly has an 'any' type

    正文从这开始~ 总览 当我们不在事件处理函数中为事件声明类型时,会产生"Parameter 'event' implicitly has an 'any' type"错误.为了解决 ...