Asp.net Core 數據庫離線文件的連接(引自“張不水”兄的研究成果。)
一、絕對路徑:
"DefaultConnection": "Data Source=(localdb)\\mssqllocaldb;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Visual Studio 2017\\Projects\\WebApplication1\\WebApplication1\\App_Data\\aspnet123.mdf;Integrated Security=True;Connect Timeout=30"
二、相對路徑:
1、修改appsettings.json文件中的"ConnectionStrings"(第3行)
"DefaultConnection": "Data Source=(localdb)\\mssqllocaldb;AttachDbFilename=%CONTENTROOTPATH%\\App_Data\\aspnet123.mdf;Integrated Security=True;Connect Timeout=30;MultipleActiveResultSets=true”
需注意的是:AttachDbFilename=%CONTENTROOTPATH%\\App_Data\\aspnet123.mdf;
使用 ContentRootPath 是將文件放置在項目目錄下而不是wwwroot目錄下,這樣更安全。
- ContentRootPath 用於包含應用程序文件。
- WebRootPath 用於包含Web服務性的內容文件。
實際使用區別如下:
ContentRoot: C:\MyApp\ WebRoot: C:\MyApp\wwwroot\
2、修改Startup.cs
原始代碼:
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); // Add application services. services.AddTransient<IEmailSender, EmailSender>(); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } }
修改后代碼
public class Startup { public Startup(IConfiguration configuration,IHostingEnvironment env) { Configuration = configuration; _env = env; } public IConfiguration Configuration { get; } public IHostingEnvironment _env { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //services.AddDbContext<ApplicationDbContext>(options => //options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); //添加修改()聲明變量conn並做相應處理 string conn = Configuration.GetConnectionString("DefaultConnection"); if (conn.Contains("%CONTENTROOTPATH%")) { conn = conn.Replace("%CONTENTROOTPATH%", _env.ContentRootPath); } //修改默認的連接服務為conn services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(conn)); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); // Add application services. services.AddTransient<IEmailSender, EmailSender>(); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } }
3、我們需要手動在項目中添加“App_data”文件夾,並復制粘貼一個標准的內容為空的.mdf文件。
為方便大家學習我這里為大家提供了示例數據庫
生成數據庫
1、雙擊Startup.cs
2、右鍵選“ 打開所在的文件夾”
3、在controller文件夾上按 shift +右鍵 選“在此處打開命令窗口”
4、命令框輸入cd.. 回車后退回上層目錄
5、輸入下面的命令
dotnet ef migrations add Initial 建立並初始化數據庫
dotnet ef database update 更新數據庫
dotnet ef migrations add xxxx 更新模型字段后需要執行此命令通知vs重新編譯表變動 xxxx為變更的任意字段名 一個就夠 系統會自動追加變更添加的其他字段
dotnet ef database update 更新數據庫
或者vs中
PM>
Enable-Migrations 啟動遷移配置
PM> Add-Migration xxxx 更新數據庫的遷移的名稱
更新模型字段后需要執行此命令通知vs重新編譯表變動 xxxx為變更的任意字段名 一個就夠 系統會自動追加變更添加的其他字段
(注意這里必須是在Models目錄中添加數據模型(類、新建項、現有項等)並重新生成后,然后添加對應的控制器和視圖后才能使用此命令,生成遷移命令后馬上使用Update-Database更新數據庫。
)
(可以多次修改生成一次遷移命令,不能多次遷移修改卻執行一次更新數據庫,只能遷移一次就更新一次。)
PM> Update-Database –TargetMigration: $InitialDatabase 回滾數據庫至初始狀態
PM> Update-Database –TargetMigration: xxxx 回滾數據庫至某個更新
PM> Update-Database
更新數據庫