首先 配置文件现在已经变成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