.net 和 core 数据库连接字符串

Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-xxxx.mdf;Initial Catalog=aspnet-xxxx;Integrated Security=True" providerName="System.Data.SqlClient"

Server=(localdb)\\mssqllocaldb; Database=xxxxx; Serve=服务器名;Database=数据库名

Server=(localdb)\\mssqllocaldb; AttachDbFilename=xxxx.mdf;Initial Catalog=xxxxx; Serve指服务器名;AttachDbFilename指连接的本地那个数据库文件,Initial Catalog指数据库名称

“AttachDbFilename=|DataDirectory|\\data.mdf”      “|DataDirectory|”代表ASP.NET项目里自动创建的App_Data文件夹并在其内创建data.mdb文件。

 

integrated security=true 采用集成验证

Trusted_Connection=True; 采用信任连接;

MultipleActiveResultSets=true  指定此数据库连接是否复用数据库内已建立的相同用户的连接。如为True时,建立数据库连接时会先查询服务器上是否已为此用户建立连接,如已建立则直接复用此连接。数据库的打开与关闭是很消耗系统的性能,利用这种对链接的关联方式可以减轻系统的负担。

Encrypt=False;是否加密;

TrustServerCertificate=True;设置为“true”以指定 适用于 SQL Server 的 Microsoft JDBC Driver 将不会验证 SQL Server SSL 证书。如果为“true”,当使用 SSL 加密通信层时,将自动信任 SQL Server SSL 证书。如果为“false”,适用于 SQL Server 的 Microsoft JDBC Driver 将验证服务器 SSL 证书。 如果服务器证书验证失败,驱动程序将引发错误并终止连接。 默认值为“false”。 当且仅当 encrypt 属性设置为“true”时,此属性仅影响服务器 SSL 证书验证。

AplicationIntent= ReadWrite;用来标记客户端发送来的请求类型(ApplicationIntent = ReadOnly)

 

Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-xxxx.mdf;Initial Catalog=aspnet-xxxx;Integrated Security=True;Trusted_Connection=True;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"

 

 

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

修改前代码

 1 public class Startup
 2     {
 3         public Startup(IHostingEnvironment env)
 4         {
 5             var builder = new ConfigurationBuilder()
 6                 .SetBasePath(env.ContentRootPath)
 7                 .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
 8                 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
 9 
10             if (env.IsDevelopment())
11             {
12                 // For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
13                 builder.AddUserSecrets<Startup>();
14             }
15 
16             builder.AddEnvironmentVariables();
17             Configuration = builder.Build();
18         }
19 
20         public IConfigurationRoot Configuration { get; }
21 
22         // This method gets called by the runtime. Use this method to add services to the container.
23         public void ConfigureServices(IServiceCollection services)
24         {
25             // Add framework services.
26             services.AddDbContext<ApplicationDbContext>(options =>
27                 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
28 
29             services.AddIdentity<ApplicationUser, IdentityRole>()
30                 .AddEntityFrameworkStores<ApplicationDbContext>()
31                 .AddDefaultTokenProviders();
32 
33             services.AddMvc();
34 
35             // Add application services.
36             services.AddTransient<IEmailSender, AuthMessageSender>();
37             services.AddTransient<ISmsSender, AuthMessageSender>();
38         }

 

修改后代码

 1 public class Startup
 2 {
 3     //添加修改   声明一个连接字符串(20行)
 4     private string _contentRootPath = "";
 5 
 6     public Startup(IHostingEnvironment env)
 7     {
 8          var builder = new ConfigurationBuilder()
 9                 .SetBasePath(env.ContentRootPath)
10                 .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
11                 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
12 
13         //添加修改(27行)
14         _contentRootPath = env.ContentRootPath;
15    
16     }
17 
18    
19     public void ConfigureServices(IServiceCollection services)
20     {
21        //添加修改(45行)声明变量conn并做相应处理
22        string conn = Configuration.GetConnectionString("DefaultConnection");
23         if(conn.Contains("%CONTENTROOTPATH%"))
24         {
25             conn = conn.Replace("%CONTENTROOTPATH%", _contentRootPath);
26         }
27        //修改默认的连接服务为conn
28       services.AddDbContext<ApplicationDbContext>(options =>
29                 options.UseSqlServer(conn));
30 
31      ...
32      }

 

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



由LocalDb 数据库升级为 MSSQLSERVER 数据库
1、为了便于管理数据库还是使用AttachDbFilename=|DataDirectory|\aspnet-xxxx.mdf(相对路径)
2、只启用
MSSQLSERVER的数据引擎。
3、修改步骤:
  打开App.config文件;
  修改<entityFramework>中的
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
改为如下
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">

并把
<parameters>节注释掉,如下

!--<parameters>
<parameter value="mssqllocaldb" />
</parameters>-->

4、程序重新编译好。

5、生产机器上安装MSSQLSERVER,把编译好的程序复制到生产机器上,执行程序即可。

 

转载于:https://www.cnblogs.com/chonghanyu/p/5709780.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值