学习ASP.NET Core Blazor编程系列六——初始化数据
学习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编程系列六——初始化数据的更多相关文章
- 学习ASP.NET Core Blazor编程系列六——新增图书(上)
学习ASP.NET Core Blazor编程系列一--综述 学习ASP.NET Core Blazor编程系列二--第一个Blazor应用程序(上) 学习ASP.NET Core Blazor编程系 ...
- 学习ASP.NET Core Blazor编程系列八——数据校验
学习ASP.NET Core Blazor编程系列一--综述 学习ASP.NET Core Blazor编程系列二--第一个Blazor应用程序(上) 学习ASP.NET Core Blazor编程系 ...
- 学习ASP.NET Core Blazor编程系列九——服务器端校验
学习ASP.NET Core Blazor编程系列一--综述 学习ASP.NET Core Blazor编程系列二--第一个Blazor应用程序(上) 学习ASP.NET Core Blazor编程系 ...
- 学习ASP.NET Core Blazor编程系列十——路由(上)
学习ASP.NET Core Blazor编程系列一--综述 学习ASP.NET Core Blazor编程系列二--第一个Blazor应用程序(上) 学习ASP.NET Core Blazor编程系 ...
- 学习ASP.NET Core Blazor编程系列二——第一个Blazor应用程序(完)
学习ASP.NET Core Blazor编程系列一--综述 学习ASP.NET Core Blazor编程系列二--第一个Blazor应用程序(上) 学习ASP.NET Core Blazor编程系 ...
- 学习ASP.NET Core Blazor编程系列十——路由(中)
学习ASP.NET Core Blazor编程系列一--综述 学习ASP.NET Core Blazor编程系列二--第一个Blazor应用程序(上) 学习ASP.NET Core Blazor编程系 ...
- 学习ASP.NET Core Blazor编程系列二——第一个Blazor应用程序(上)
学习ASP.NET Core Blazor编程系列一--综述 一.概述 Blazor 是一个生成交互式客户端 Web UI 的框架: 使用 C# 代替 JavaScript 来创建信息丰富的交互式 U ...
- 学习ASP.NET Core Blazor编程系列二——第一个Blazor应用程序(中)
学习ASP.NET Core Blazor编程系列一--综述 学习ASP.NET Core Blazor编程系列二--第一个Blazor应用程序(上) 四.创建一个Blazor应用程序 1. 第一种创 ...
- 学习ASP.NET Core Blazor编程系列二——第一个Blazor应用程序(下)
学习ASP.NET Core Blazor编程系列一--综述 学习ASP.NET Core Blazor编程系列二--第一个Blazor应用程序(上) 学习ASP.NET Core Blazor编程系 ...
随机推荐
- javascript原生style属性分析
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="U ...
- Python 爬取汽车之家口碑数据
本文仅供学习交流使用,如侵立删!联系方式见文末 汽车之家口碑数据 2021.8.3 更新 增加用户信息参数.认证车辆信息等 2021.3.24 更新 更新最新数据接口 2020.12.25 更新 添加 ...
- 一文带你掌握Spring Web异常处理方式
一.前言 大家好,我是 去哪里吃鱼 ,也叫小张. 最近从单位离职了,离开了五年多来朝朝夕夕皆灯火辉煌的某网,激情也好悲凉也罢,觥筹场上屡屡物是人非,调转过事业部以为能换种情绪,岂料和下了周五的班的前同 ...
- 数据结构与算法【Java】02---链表
前言 数据 data 结构(structure)是一门 研究组织数据方式的学科,有了编程语言也就有了数据结构.学好数据结构才可以编写出更加漂亮,更加有效率的代码. 要学习好数据结构就要多多考虑如何将生 ...
- Luogu5019 铺设道路 (贪心)
水题,水得好无语 #include <iostream> #include <cstdio> #include <cstring> #include <alg ...
- Linux 08 磁盘管理
参考源 https://www.bilibili.com/video/BV187411y7hF?spm_id_from=333.999.0.0 版本 本文章基于 CentOS 7.6 概述 Linux ...
- 常用类--String
一.String 1.1 String是不可变对象 String的底层是一个 char类型字符数组 String类是final修饰的,不能被继承,不能改变,但引用可以重新赋值 String采用的编码方 ...
- jsp获取下拉框组件的值
jsp获取下拉框组件的值 1.首先,写一个带有下拉框的前台页 1 <%@ page language="java" contentType="text/html; ...
- Docke 搭建 apache2 + php8 + MySQL8 环境
Docker 安装 执行 Docker 安装命令 curl -fsSL https://get.docker.com/ | sh 启动 Docker 服务 sudo service docker st ...
- Linux 禁止root远程登录解决办法
linux中root用户是超级管理员,可以针对root用户暴力破解密码,这样很不安全,工作中我们一般禁止root用户直接远程登陆,开设一个或多个普通用户,只允许登陆普通用户,如果有需要用root用户, ...