学习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编程系 ...
随机推荐
- netcore 非注入全局获取配置文件
在netcore开发中,最常见的就是注入,比如想获取appsettings.json的内容,我们就需要去注入,然后在controller里面去获取,但是我们如果想要在service中使用appsett ...
- python 日志类
简介 在所有项目中必不可少的一定是日志记录系统,python为我们提供了一个比较方便的日志模块logging,通常,我们都会基于此模块编写一个日志记录类,方便将项目中的日志记录到文件中. loggin ...
- 为美多商城(Django2.0.4)添加基于websocket的实时通信,主动推送,聊天室及客服系统
原文转载自「刘悦的技术博客」https://v3u.cn/a_id_67 websocket是个啥? webSocket是一种在单个TCP连接上进行全双工通信的协议 webSocket使得客户端和服务 ...
- 程序思想中的冒泡法在python和1200PLC中scl高级编程中的应用
冒泡排序:是计算机科学领域里面的一种算法. header 这个算法名字的由来是因为在执行算法的时候越小的元素会经由交换慢慢"浮"到数列的顶端(升序或降序排列),就如同碳酸饮料中二氧 ...
- 使用 Liquibase 管理数据库版本 - SpringBoot 2.7 .2 实战基础
优雅哥 SpringBoot 2.7 .2 实战基础 - 05 -使用 Liquibase 管理数据库版本 在企业开发中,数据库版本管理好像是一个伪命题,大多项目都是通过 Power Designer ...
- Java SE 10 新增特性
Java SE 10 新增特性 作者:Grey 原文地址:Java SE 10 新增特性 源码 源仓库: Github:java_new_features 镜像仓库: GitCode:java_new ...
- virsh edit 很慢 的bug
创建虚拟机,发现virsh edit很慢. strace的结果: 09:26:03 close(10) = -1 EBADF (Bad file descriptor)09:26:03 close(1 ...
- QtCreator使用AStyle配置VS默认编辑代码风格
基础配置和下载 基础配置和下载,随便找一个教程就行 下面贴出我的配置 --style=allman indent=spaces=4 indent-switches indent-preproc-blo ...
- C#运用事件步骤(usual)
1.声明一个委托 委托跟Main函数在同一个NameSpace中.或者在class A中. delegate void delegateFuncA; 2.声明一个事件 在class A中 public ...
- 第五十三篇:Vue安装Element ui
好家伙,之前写的一篇过时了,用不了了,更新一波 (已新建一个vue项目) 1. 在项目目录下执行:npm i element-ui -S 2. 在main.js中写入 import ElementUI ...