ASP.NET Core 中文文档 第二章 指南(4.5)使用 SQL Server LocalDB
原文:Working with SQL Server LocalDB
作者:Rick Anderson
翻譯: 魏美娟(初見)
校對: 孟帥洋(書緣)、張碩(Apple)、許登洋(Seay)
ApplicationDbContext 類負責連接數據庫并將 Movie 對象和數據記錄進行映射。 Startup.cs 文件中,數據庫上下文是在 ConfigureServices 方法中用 Dependency Injection 容器進行注冊的。
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) {// Add framework services.services.AddDbContext<ApplicationDbContext>(options => //手動高亮options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); //手動高亮ASP.NET Core Configuration 系統讀取 ConnectionString 。在本地開發模式下,它會從 appsettings.json 文件中獲取連接字符串。
{"ConnectionStrings": {"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-MvcMovie-7db2893b-375e-48bd-86a3-bb9779b72ebe;Trusted_Connection=True;MultipleActiveResultSets=true" //手動高亮},"Logging": {"IncludeScopes": false,當你部署應用程序到測試服務器或者生產服務器時,你可以使用環境變量或者另一種方法來設置實際 SQL Server 數據庫的連接字符串。更多參考 Configuration 。
SQL Server Express LocalDB
LocalDB是針對程序開發階段使用的一個SQL Server Express輕量級版本的數據庫引擎。 因為LocalDB在用戶模式下啟動、執行,所以它沒有復雜的配置。默認情況下,LocalDB數據庫創建的 “*.mdf” 文件在 C:/Users/<user> 目錄下。
從 View 菜單中,打開SQL Server對象資源管理器(SQL Server Object Explorer ,(SSOX)).
右擊 Movie 表 > 視圖設計器(View Designer)
注意鑰匙圖標后面的 ID。默認情況下,EF將命名為 ID 的屬性作為主鍵。
- 右擊 Movie 表 > 查看數據(View Data)
填充數據庫
在 Models 文件夾中創建一個名叫 SeedData 的新類。用以下代碼替換生成的代碼。
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using MvcMovie.Data; using System; using System.Linq;namespace MvcMovie.Models {public static class SeedData{public static void Initialize(IServiceProvider serviceProvider){using (var context = new ApplicationDbContext(serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>())){if (context.Movie.Any()){return; // DB has been seeded}context.Movie.AddRange(new Movie{Title = "When Harry Met Sally",ReleaseDate = DateTime.Parse("1989-1-11"),Genre = "Romantic Comedy",Price = 7.99M},new Movie{Title = "Ghostbusters ",ReleaseDate = DateTime.Parse("1984-3-13"),Genre = "Comedy",Price = 8.99M},new Movie{Title = "Ghostbusters 2",ReleaseDate = DateTime.Parse("1986-2-23"),Genre = "Comedy",Price = 9.99M},new Movie{Title = "Rio Bravo",ReleaseDate = DateTime.Parse("1959-4-15"),Genre = "Western",Price = 3.99M});context.SaveChanges();}}} }注意,如果數據庫上下文中存在 movies,填充初始化器返回。
if (context.Movie.Any()){return; // DB has been seeded //手動高亮}在 Startup.cs 文件中的 Configure 方法最后添加填充初始化器。
app.UseMvc(routes =>{routes.MapRoute(name: "default",template: "{controller=Home}/{action=Index}/{id?}");});SeedData.Initialize(app.ApplicationServices); //手動高亮 }測試應用程序
- 刪除數據庫中的所有記錄。你可以直接在瀏覽器中點擊刪除鏈接或者在 SSOX(SQL Server對象資源管理器)中做這件事。
- 強制應用程序初始化(在 Startup 類中調用方法),這樣填充方法會自動運行。為了強制初始化,IIS Express必須先停止,然后重新啟動。可以用下列的任何一個方法來實現:
注意
如果是數據庫沒有初始化,在 if (context.Movie.Any()) 這行設置斷點,并開始調試
應用程序顯示了被填充的數據.
返回目錄
轉載于:https://www.cnblogs.com/dotNETCoreSG/p/aspnetcore-2_4_5-working-with-sql.html
總結
以上是生活随笔為你收集整理的ASP.NET Core 中文文档 第二章 指南(4.5)使用 SQL Server LocalDB的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: POJ2503 UVA10282 Bab
- 下一篇: another app is curre