1. 程式人生 > >.Net Core 本地數據庫連接的實現

.Net Core 本地數據庫連接的實現

onf entity res str 項目 action efault migration nta

.Net Core 本地數據庫連接的實現

參考:https://www.bbsmax.com/A/WpdKXj7NzV/, 做了一點小的修正。

一、絕對路徑:

"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服務性的內容文件。

實際使用區別如下:

a) ContentRoot: C:\MyApp\

b) 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("ApplicationDbContext");

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文件。

4、Add-Migration Attach

Update-Database

順利得到所要本地連接的數據庫。

.Net Core 本地數據庫連接的實現