按照教程创建了一个 Blazor Server 项目
首页在启动时,从MenuService 获取菜谱列表
menus = await Mmservise.GetMenuAsync(DateTime.Now);
做组件时候,MenuService是这样写的
public class MenuService { public Task< List<Menu> > GetMenuAsync(DateTime startDate) { List<Menu> meuns = new List<Menu>(); string[] days = new string[] { "2021-02-06", "2021-02-07", "2021-02-08" }; var rng = new Random(); foreach (string daystr in days) { Menu a = new Menu { ID = Guid.NewGuid(), Name = "红烧鱼", MenuDay = Convert.ToDateTime(daystr), DefaultNamber = 1, Price = rng.Next(5, 30), Type = "午餐" }; Menu b = new Menu { ID = Guid.NewGuid(), Name = "大盘鸡", MenuDay = Convert.ToDateTime(daystr), DefaultNamber = 1, Price = rng.Next(5, 30), Type = "午餐" }; Menu c = new Menu { ID = Guid.NewGuid(), Name = "烤肉", MenuDay = Convert.ToDateTime(daystr), DefaultNamber = 1, Price = rng.Next(5, 30), Type = "午餐" }; Menu d = new Menu { ID = Guid.NewGuid(), Name = "油条豆浆", MenuDay = Convert.ToDateTime(daystr), DefaultNamber = 1, Price = rng.Next(5, 30), Type = "早餐" }; Menu e = new Menu { ID = Guid.NewGuid(), Name = "炸酱面", MenuDay = Convert.ToDateTime(daystr), DefaultNamber = 1, Price = rng.Next(5, 30), Type = "晚餐" }; meuns.Add(a); meuns.Add(b); meuns.Add(c); meuns.Add(d); meuns.Add(e); } return Task.FromResult(meuns); } }
在 陈超超 的教程里,是新建立了 WebAPI接口 给 APP 提供后台支持, 我想着既然已经是 Blazor Server 项目了,能不能直接在 Server 用 EF 呢。
尝试过程:
1) 创建 DbContext
public class BlazorApp0206Context: DbContext { public DbSet<Menu> Menus { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder options) => options.UseSqlite("Data Source=BlazorApp0206.db"); }
2)迁移数据库
Install-Package Microsoft.EntityFrameworkCore.Tools Add-Migration InitialCreate0209 Update-Database
3)修改 MenuService
public class MenuService { public Task< List<Menu> > GetMenuAsync(DateTime startDate) { using (var db = new BlazorApp0206Context()) { var meuns = db.Menus.ToList<Menu>(); return Task.FromResult(meuns); } } } }
4) 工作目录不一致 的问题,直接照抄文档:
运行 .NET Core 控制台应用时,Visual Studio 使用不一致的工作目录。 (请参阅 dotnet/project-system#3619)这会导致引发异常: 无此类表格:博客 。 更新工作目录:
右键单击项目,并选择“编辑项目文件”
在 TargetFramework 属性下方,添加以下内容:
XML
<StartWorkingDirectory>$(MSBuildProjectDirectory)</StartWorkingDirectory>
保存该文件
现在可以运行应用:
“调试”>“开始执行(不调试)”
最后来个截图
参考资料:
https://docs.microsoft.com/zh-cn/aspnet/core/blazor/blazor-server-ef-core?view=aspnetcore-5.0
https://docs.microsoft.com/zh-cn/ef/core/get-started/overview/first-app?tabs=visual-studio
https://www.cnblogs.com/MSReactor/p/14380219.html