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

最新文章

  1. 一个基于jQuery的移动端条件选择查询插件(原创)
  2. C#实现哥德巴赫猜想
  3. git 简单使用
  4. Java中Map集合的四种访问方式(转)
  5. Hibernate SQL查询 addScalar()或addEntity()
  6. MobClick详解
  7. python 批量爬取代理ip
  8. Python基础教程【读书笔记】 - 2016/7/24
  9. HDU 3047 Zjnu Stadium(带权并查集)
  10. hihocoder 1310 岛屿
  11. verilog中的function用法与例子
  12. HDOJ/HDU 2700 Parity(奇偶判断~)
  13. C++Builder中MessageBox的基本用法
  14. code force 401B. Game of Credit Cards
  15. 【批处理学习笔记】第十三课:常用dos命令(3)
  16. Picasso 图片加载库
  17. 35.在CSS中 只用一个 DOM 元素就能画出国宝熊猫
  18. 【SPL标准库专题(4)】 Datastructures:SplDoublyLinkedList
  19. WP8.1学习系列(第六章)——中心控件Hub面板部分交互UX
  20. python学习笔记011——内置函数sorted()

热门文章

  1. TurnipBit之DIY无线遥控智能小车
  2. ubuntu16.04+eigen3安装
  3. SQLAlchemy基础操作一
  4. MySQL5.7新特性:lossless replication 无损复制
  5. 《深入解剖Yii2框架》前言
  6. 【算法】赫夫曼树(Huffman)的构建和应用(编码、译码)
  7. CCNA笔记(3)
  8. 深入理解 react-router 路由系统
  9. 2329: [HNOI2011]括号修复
  10. HDU1097-A hard puzzle-快速幂+取模