• 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

  • 相关阅读:
    kendo DataSource
    动态改变kendoGrid的数据、列和基础设置
    kendoValidator 验证
    块级元素的水平、垂直居中
    kendoUpload 上传控件
    916数据结构额外考题
    916 数据结构与算法考纲
    英语六级作文翻译
    考研线性代数
    蓝牙室内定位技术原理
  • 原文地址:https://www.cnblogs.com/Gavin-wang/p/5885065.html
Copyright © 2020-2023  润新知