【问题标题】:EF Add-Migration: connection string issue using app.configEF Add-Migration:使用 app.config 的连接字符串问题
【发布时间】: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


【解决方案1】:

公共类 BloggingContext : DbContext {

    public BloggingContext (DbContextOptions<BloggingContext> options) : base(options)
    {

    }
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}

添加 Startup.cs 公共无效配置服务(IServiceCollection 服务) { services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); }

【讨论】:

    【解决方案2】:

    这是我获得 ConnectionString 的方式。不确定这是否适合您。

    App.config

    <connectionStrings>
    <add name="con" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=PRWSolution2020;Integrated Security=True" providerName="System.Data.SqlClient"/>
    

    DBContext

    public DbSet<Machine> Machines { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<ContractDetail> ContractDetails { get; set; }
        public DbSet<TimeSheet> TimeSheets { get; set; }
        public DbSet<MachineClient> MachineClients { get; set; }
        public DbSet<ServiceReport> ServiceReports { get; set; }
    
        public PRWContext()
            : base("name=con")
        {
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-01
      • 2021-07-26
      • 2015-04-06
      • 1970-01-01
      • 2012-10-07
      • 2019-03-10
      • 2023-04-04
      相关资源
      最近更新 更多