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应用程序。使用鼠标右键点击浏览器中左边的菜单栏中的“图书列表”菜单,在浏览器中显示图书信息。如下图。
标签:
留言评论