【发布时间】:2020-09-19 20:28:23
【问题描述】:
我正在尝试一步一步地学习一些关于 EF 的知识,从今天早上开始我就一直坚持这个 :-| 如果我尝试“添加迁移”,则一切正常
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer(@"Server=MyServer;Database=MyDb;User Id=MyUser;Password=MyPsw");
}
但我尝试将连接字符串移动到 app.config 并修改上面的代码如下:
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer(ConfigurationManager.ConnectionStrings["db"].ConnectionString);
}
我还添加了“使用 System.Configuration;”
应用程序配置:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="db"
providerName="System.Data.SqlClient"
connectionString="Server=MyServer;Database=MyDb;User Id=MyUser;Password=MyPsw"/>
</connectionStrings>
</configuration>
但在这种情况下它不起作用,当我尝试“添加迁移”时,操作失败并且在 PMC 中出现“对象引用未设置为对象的实例。”。可能是什么问题?
(我知道在 app.config 中存储 User/psw 不好,这将是下一步改进...)
提前致谢。
【问题讨论】:
-
这真的和
语言有关吗?也许您应该使用 标记? -
你应该appsettings.json
-
您是否有覆盖您的连接字符串的 App.Development.Config 或其他环境特定的 App.config 文件?
-
不这么认为,刚从一个WPF空应用程序开始只添加3个类和App.config文件..
-
看起来与您在使用 WPF docs.microsoft.com/en-us/answers/questions/20091/…时遇到的问题相同
标签: c# sql-server entity-framework connection-string database-migration