按照教程建立了一個 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