码迷,mamicode.com
首页 > 数据库 > 详细

.Net Core 本地数据库连接的实现

时间:2019-01-08 22:01:06      阅读:827      评论:0      收藏:0      [点我收藏+]

标签:项目目录   https   ring   request   handle   pipe   otp   att   rtu   

.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 本地数据库连接的实现

标签:项目目录   https   ring   request   handle   pipe   otp   att   rtu   

原文地址:https://www.cnblogs.com/dlhjwang/p/10241522.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!