ASP.NET Core 中文文档 第二章 指南(4.5)使用 SQL Server LocalDB
原文:Working with SQL Server LocalDB
作者:Rick Anderson
翻譯: 魏美娟(初見(jiàn))
校對(duì): 孟帥洋(書(shū)緣)、張碩(Apple)、許登洋(Seay)
ApplicationDbContext 類負(fù)責(zé)連接數(shù)據(jù)庫(kù)并將 Movie 對(duì)象和數(shù)據(jù)記錄進(jìn)行映射。 Startup.cs 文件中,數(shù)據(jù)庫(kù)上下文是在 ConfigureServices 方法中用 Dependency Injection 容器進(jìn)行注冊(cè)的。
// 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 => //手動(dòng)高亮options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); //手動(dòng)高亮ASP.NET Core Configuration 系統(tǒng)讀取 ConnectionString 。在本地開(kāi)發(fā)模式下,它會(huì)從 appsettings.json 文件中獲取連接字符串。
{"ConnectionStrings": {"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-MvcMovie-7db2893b-375e-48bd-86a3-bb9779b72ebe;Trusted_Connection=True;MultipleActiveResultSets=true" //手動(dòng)高亮},"Logging": {"IncludeScopes": false,當(dāng)你部署應(yīng)用程序到測(cè)試服務(wù)器或者生產(chǎn)服務(wù)器時(shí),你可以使用環(huán)境變量或者另一種方法來(lái)設(shè)置實(shí)際 SQL Server 數(shù)據(jù)庫(kù)的連接字符串。更多參考 Configuration 。
SQL Server Express LocalDB
LocalDB是針對(duì)程序開(kāi)發(fā)階段使用的一個(gè)SQL Server Express輕量級(jí)版本的數(shù)據(jù)庫(kù)引擎。 因?yàn)長(zhǎng)ocalDB在用戶模式下啟動(dòng)、執(zhí)行,所以它沒(méi)有復(fù)雜的配置。默認(rèn)情況下,LocalDB數(shù)據(jù)庫(kù)創(chuàng)建的 “*.mdf” 文件在 C:/Users/<user> 目錄下。
從 View 菜單中,打開(kāi)SQL Server對(duì)象資源管理器(SQL Server Object Explorer ,(SSOX)).
右擊 Movie 表 > 視圖設(shè)計(jì)器(View Designer)
注意鑰匙圖標(biāo)后面的 ID。默認(rèn)情況下,EF將命名為 ID 的屬性作為主鍵。
- 右擊 Movie 表 > 查看數(shù)據(jù)(View Data)
填充數(shù)據(jù)庫(kù)
在 Models 文件夾中創(chuàng)建一個(gè)名叫 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();}}} }注意,如果數(shù)據(jù)庫(kù)上下文中存在 movies,填充初始化器返回。
if (context.Movie.Any()){return; // DB has been seeded //手動(dòng)高亮}在 Startup.cs 文件中的 Configure 方法最后添加填充初始化器。
app.UseMvc(routes =>{routes.MapRoute(name: "default",template: "{controller=Home}/{action=Index}/{id?}");});SeedData.Initialize(app.ApplicationServices); //手動(dòng)高亮 }測(cè)試應(yīng)用程序
- 刪除數(shù)據(jù)庫(kù)中的所有記錄。你可以直接在瀏覽器中點(diǎn)擊刪除鏈接或者在 SSOX(SQL Server對(duì)象資源管理器)中做這件事。
- 強(qiáng)制應(yīng)用程序初始化(在 Startup 類中調(diào)用方法),這樣填充方法會(huì)自動(dòng)運(yùn)行。為了強(qiáng)制初始化,IIS Express必須先停止,然后重新啟動(dòng)。可以用下列的任何一個(gè)方法來(lái)實(shí)現(xiàn):
注意
如果是數(shù)據(jù)庫(kù)沒(méi)有初始化,在 if (context.Movie.Any()) 這行設(shè)置斷點(diǎn),并開(kāi)始調(diào)試
應(yīng)用程序顯示了被填充的數(shù)據(jù).
返回目錄
轉(zhuǎn)載于:https://www.cnblogs.com/dotNETCoreSG/p/aspnetcore-2_4_5-working-with-sql.html
總結(jié)
以上是生活随笔為你收集整理的ASP.NET Core 中文文档 第二章 指南(4.5)使用 SQL Server LocalDB的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: POJ2503 UVA10282 Bab
- 下一篇: another app is curre