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?}");
});
}
}
 到2.0的时候,其实IHostingEnvironment还是可以注入的。
http://www.learnentityframeworkcore.com/configuration/fluent-api
 

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 更新数据库

.net 和 core2.0 数据库连接字符串的更多相关文章

  1. Microsoft ACE OLEDB 12.0 数据库连接字符串

    Excel 97-2003 Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myOldExcelFile.xls;Extended ...

  2. .Net Framework下对Dapper二次封装迁移到.Net Core2.0遇到的问题以及对Dapper的封装介绍

    今天成功把.Net Framework下使用Dapper进行封装的ORM成功迁移到.Net Core 2.0上,在迁移的过程中也遇到一些很有意思的问题,值得和大家分享一下.下面我会还原迁移的每一个过程 ...

  3. 从壹开始前后端分离【 .NET Core2.0 +Vue2.0 】框架之七 || API项目整体搭建 6.2 轻量级ORM

    更新 1.在使用的时候,特别是更新数据的时候,如果不知道哪里有问题,可以查看数据库 和 实体类 的字段,是否大小写一致,比如 name 和 Name 2.在使用Sqlsugar 的 CodeFirst ...

  4. .Net Core2.0下使用Dapper遇到的问题

    今天成功把.Net Framework下使用Dapper进行封装的ORM成功迁移到.Net Core 2.0上,在迁移的过程中也遇到一些很有意思的问题,值得和大家分享一下.下面我会还原迁移的每一个过程 ...

  5. Net Core2.0下使用Dapper

    Net Core2.0下使用Dapper 今天成功把.Net Framework下使用Dapper进行封装的ORM成功迁移到.Net Core 2.0上,在迁移的过程中也遇到一些很有意思的问题,值得和 ...

  6. ADO.NET .net core2.0添加json文件并转化成类注入控制器使用 简单了解 iTextSharp实现HTML to PDF ASP.NET MVC 中 Autofac依赖注入DI 控制反转IOC 了解一下 C# AutoMapper 了解一下

    ADO.NET   一.ADO.NET概要 ADO.NET是.NET框架中的重要组件,主要用于完成C#应用程序访问数据库 二.ADO.NET的组成 ①System.Data  → DataTable, ...

  7. EF--Codefirst 加密数据库连接字符串

    http://www.tuicool.com/articles/QvYbEn 一.EF,CodeFirst加密SQL连接符 public LifeHelpContext() : base(" ...

  8. 【转】ASP.NET数据库连接字符串总结

    来源:http://blog.csdn.net/lutinghuan/article/details/5973897 ASP.NET数据库连接字符串总结 一.使用OleDbConnection对象连接 ...

  9. web.config connectionStrings 数据库连接字符串的解释

    先来看一下默认的连接SQL Server数据库配置<connectionStrings>   <add name="LocalSqlServer" connect ...

随机推荐

  1. golang 多维数组

    具体的题目如下:(就是将多维数组的行列互换) A multi-dimensional array is an array of arrays. 2-dimensional arrays are the ...

  2. [js高手之路]从零开始打造一个javascript开源框架gdom与插件开发免费视频教程连载中

    百度网盘下载地址:https://pan.baidu.com/s/1kULNXOF 优酷土豆观看地址:http://v.youku.com/v_show/id_XMzAwNTY2MTE0MA==.ht ...

  3. eclipse的各种错误和解决方法

    1.cannot import xxx because the project name is in use

  4. Hyperledger Fabric 1.0 从零开始(十二)——fabric-sdk-java应用

    Hyperledger Fabric 1.0 从零开始(十)--智能合约 Hyperledger Fabric 1.0 从零开始(十一)--CouchDB 上述两章,最近网上各路大神文章云集,方案多多 ...

  5. Linux 常见目录与区别

    .   代表此层目录 ..   代表上一层目录 -   代表前一个工作目录 ~   代表『目前用户身份』所在的家目录

  6. [转载]解决sudo: sorry, you must have a tty to run sudo

    前几天遇到一个问题,在一个终端中调用另一个shell,始终是无法执行的,后来捕捉到报错信息为sudo: sorry, you must have a tty to run sudo,后来,在网上了解到 ...

  7. 大数据分析中Redis怎么做到220万ops

    大数据时代,海量数据分析就像吃饭一样,成为了我们每天的工作.为了更好的为公司提供运营决策,各种抖机灵甚至异想天开的想法都会紧跟着接踵而来!业务多变,决定了必须每天修改系统,重新跑数据,这就要求极高的海 ...

  8. dump_stack 分析使用

    dump_stack是用来回溯内核运行的信息的,打印内核信息堆栈段: dump_stack原型: void dump_stack(void); 1.使用这个功能时需要将内核配置勾选上: make me ...

  9. C# 获取当前方法的名称空间、类名和方法名称

    1.(new StackTrace()).GetFrame(1) // 0为本身的方法:1为调用方法2.(new StackTrace()).GetFrame(1).GetMethod().Name; ...

  10. codeforces A. Orchestra B. Island Puzzle

    A. Orchestra time limit per test 2 seconds memory limit per test 256 megabytes input standard input ...