zoukankan      html  css  js  c++  java
  • ENTITYFRAMEWORKCORE 二使用配置文件来配置数据库链接

    首先 配置文件现在已经变成appsettings.json,

    先添加一个连接字符串

     "ConnectionStrings": {
        "PWDatabase": "Data Source=172.28.8.120;Initial Catalog=WebPW;User ID=sa;Password=Windows2008;"
      }

    然后 修改Startup.cs 的ConfigureServices方法。

    将以前的代码

       services.AddDbContext<WebPWContext>();

    修改为

     public void ConfigureServices(IServiceCollection services)
            {
                // Add framework services.
                services.AddDbContext<WebPWContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("PWDatabase")));
                services.AddMvc();
            }

    需要添加引用

    using Microsoft.EntityFrameworkCore;

    然后修改 生成的“***Context.cs”文件 

    删掉下面的方法, 

       protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
    #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
               optionsBuilder.UseSqlServer(@"Data Source=172.28.8.120;Initial Catalog=WebPW;User ID=sa;Password=Windows2008");
              
            }

    添加方法

      public WebPWContext(DbContextOptions<WebPWContext> options)
                : base(options)
            { }

    参考文档 https://docs.efproject.net/en/latest/platforms/aspnetcore/existing-db.html

  • 相关阅读:
    OneSQL安装
    Dropbox可伸缩性设计最佳实践分享
    软件开发实践的24条军规
    最精彩的英语学习经验总结:俺的英语之路
    Facebook和Google如何激发工程师的创造力
    十种更好的表达“你的代码写的很烂”的方法
    一次java程序的重构
    漂亮代码
    一段代码引发的思考
    最难忘的Bug调试经历
  • 原文地址:https://www.cnblogs.com/Gavin-wang/p/5885065.html
Copyright © 2011-2022 走看看