.net 和 core2.0 数据库连接字符串

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 更新数据库
posted @ 2017-09-29 16:04  沉默种子  阅读(3237)  评论(0编辑  收藏  举报