.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目录下,这样更安全。
实际使用区别如下:
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
顺利得到所要本地连接的数据库。
原文:https://www.cnblogs.com/dlhjwang/p/10241522.html